Set IHostingEnvironment to unit test

I am currently upgrading a project from .NET Core RC1 to the new version of RTM 1.0. In RC1, there was an IApplicationEnvironment , which was replaced by IHostingEnvironment in version 1.0

In RC1, I could do it

 public class MyClass { protected static IApplicationEnvironment ApplicationEnvironment { get;private set; } public MyClass() { ApplicationEnvironment = PlatformServices.Default.Application; } } 

Does anyone know how to achieve this in version 1.0?

 public class MyClass { protected static IHostingEnvironment HostingEnvironment { get;private set; } public MyClass() { HostingEnvironment = ???????????; } } 
+8
source share
2 answers

You can mock IHostEnvironment with a fake structure, if necessary, or create a fake version by implementing an interface.

Give such a class ...

 public class MyClass { protected IHostingEnvironment HostingEnvironment { get;private set; } public MyClass(IHostingEnvironment host) { HostingEnvironment = host; } } 

You can customize the unit test example with Moq ...

 public void TestMyClass() { //Arrange var mockEnvironment = new Mock<IHostingEnvironment>(); //...Setup the mock as needed mockEnvironment .Setup(m => m.EnvironmentName) .Returns("Hosting:UnitTestEnvironment"); //...other setup for mocked IHostingEnvironment... //create your SUT and pass dependencies var sut = new MyClass(mockEnvironment.Object); //Act //...call you SUT //Assert //...assert expectations } 
+12
source

In general, since IHostingEnvironment is just an interface, you can simply mock it to bring back whatever you want.

If you use TestServer in your tests, the best way to mock is to use the WebHostBuilder.Configure method. Something like that:

 var testHostingEnvironment = new MockHostingEnvironment(); var builder = new WebHostBuilder() .Configure(app => { }) .ConfigureServices(services => { services.TryAddSingleton<IHostingEnvironment>(testHostingEnvironment); }); var server = new TestServer(builder); 
+3
source

All Articles