Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the IHostingEnvironment in unit test

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

In RC1 I could do this

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

Does anyone know how to achieve this in v1.0?

public class MyClass {     protected static IHostingEnvironment HostingEnvironment { get;private set; }      public MyClass()     {         HostingEnvironment = ???????????;     } } 
like image 815
Bill Posters Avatar asked Jul 01 '16 00:07

Bill Posters


People also ask

What is IHostingEnvironment?

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.


2 Answers

You can mock the IHostEnvironment using a mocking framework if needed or create a fake version by implementing the interface.

Give a class like this...

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

You can setup a unit test example using 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 } 
like image 186
Nkosi Avatar answered Sep 19 '22 21:09

Nkosi


Using Microsoft.Extensions.Hosting (which is one of the included packages in ASP.NET Core), you can use:

IHostEnvironment env =      new HostingEnvironment { EnvironmentName = Environments.Development }; 
like image 39
Shimmy Weitzhandler Avatar answered Sep 19 '22 21:09

Shimmy Weitzhandler