4

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
Matt DeKrey
  • 11,582
  • 5
  • 54
  • 69

1 Answers1

4

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.

tugberk
  • 57,477
  • 67
  • 243
  • 335
  • Yeah, I did try injecting it through the constructor, but I didn't know about the static service locator. And it works! (Not sure how I feel about knowing that there's a static service locator...) – Matt DeKrey May 07 '15 at 23:24
  • @MattDeKrey I agree and as you know, they don't advertise that it's there. I am not sure if they will remove it at the end. – tugberk May 08 '15 at 07:44
  • 1
    @MattDeKrey opened up an issue for xUnit: https://github.com/xunit/dnx.xunit/issues/30 – tugberk May 08 '15 at 07:48
  • Interesting that @DavidFowler had the same request and is solving it the same way. – Matt DeKrey May 08 '15 at 16:39