Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the ContentRootPath or getting IHostingEnvironment in a xunit context for .NET core

I'm creating xunit tests for .NET core (net46 framework) and I'm having a problem getting the root path of the application, so I can locate things such as appsettings.json.

Can someone please explain how I can achieve one of the following:

  • Get an instance of IHostingEnvironment

  • Retrieve the absolute path of the .NET project containing the xunit test, so I can implement IHostingEnvironment myself.

It might be a very simple problem, I just can't seem to find a good solution.

like image 854
Nikola Schou Avatar asked Aug 12 '16 08:08

Nikola Schou


People also ask

Does xUnit work with .NET core?

The xUnit.net test runner that we've been using supports . NET Core 1.0 or later, . NET 5.0 or later, and . NET Framework 4.5.

How do I get the root path in .NET core?

The Application Base (Root) path is available in the ContentRootPath property of the interfaces IHostingEnvironment (. Net Core 2.0) and IWebHostEnvironment (. Net Core 3.0) in ASP.Net Core. The IHostingEnvironment is an interface for .

What is IHostingEnvironment .NET core?

The IHostingEnvironment is an interface for . Net Core 2.0. The IHostingEnvironment interface need to be injected as dependency in the Controller and then later used throughout the Controller. The IHostingEnvironment interface have two properties.

How do you write xUnit test cases in .NET core?

To write a test you simply create a public method that returns nothing and then decorate it with the Fact attribute. Inside that method you can put whatever code you want but, typically, you'll create some object, do something with it and then check to see if you got the right result using a method on the Assert class.


1 Answers

As far as I remember injecting IHostingEnvironment in an XUnit test is not possible.

This is not ideal, but you could do something like this (ex: SetBasePath):

var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("remoteDeploymentConfig.json")
        .AddUserSecrets()
        .AddEnvironmentVariables()
        .Build();

This solution works because if you were to do dotnet test you need to do it from within the project directory itself as the test here corresponds to the xunit package of that project.

like image 96
Kiran Avatar answered Oct 01 '22 21:10

Kiran