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.
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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With