Search code examples
asp.net-corexunitxunit2

How do I access the IApplicationEnvironment from a unit test?


How can I access the IApplicationEnvironment from an xUnit 2 unit test?

There are several scenarios where I think I need this, including:

  • Read from a non-embedded configuration file built with the unit tests
  • Create and write files relating to the unit tests

Solution

  • Well, it's not ideal but you can use the static service locator to get to it:

    var appEnv = CallContextServiceLocator.Locator.ServiceProvider
        .GetService(typeof(IApplicationEnvironment)) as IApplicationEnvironment;
    

    I am not sure if xUnit injects framework dependencies in through the constructor and I bet it doesn't. If it does though (which would be perfect), you can just inject it into the test class through its constructor.