Set the IHostingEnvironment in unit test

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
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)