Kaladin
Kaladin

Reputation: 803

OWIN Integration testing - HttpContext is null

I have OWIN Web API app that I am trying to integration test. In order to do this I am creating a server in memory like so:

    private TestServer _server;

    [TestInitialize]
    public void Intitialize()
    {
        _server = TestServer.Create<Startup>();
    }

Integration test:

  [TestMethod]
  public async Task Test_Controller()
  {
      //Act
      var response = await _server.HttpClient.GetAsync("/controller/test");

      //Assert
      Assert.AreEqual(HttpStatusCode.Ok, response.StatusCode);
   }

In my controller I am trying to access some information from the HttpContext, unfortunately, this is always null during the integration test and therefore it throws an exception.

Is there anyway I can mock the the httpcontext during my integration tests?

Upvotes: 2

Views: 1437

Answers (1)

flo scheiwiller
flo scheiwiller

Reputation: 2706

You have a Web-App CodeBase with owin compatibility, hosted in IIS. You are now adding Integration-Test and are using a In-Memory Instance of your Web-App.

As stated before, your Integration Tests won't exaclty match with your IIS-Hosted WebApp. IIS may run some HTTP-Modules that won't be executed from your Owin-Host. HttpContext on None-IIS-Hosting is missing too.

In case you just wan't to get rid of the NullReference-Exception that hits you when you use HttpContext, consider updating your codebase and find a replacement for HttpContext. (e.g.: for principal, use requestContext)

On the Scenario you need your custom Context-Object and require to inject a Stub/Mock into your Owin-Host: Inject behavior in the startup of your in-memory host:

_server = Microsoft.Owin.Hosting.WebApp.Start("url", (appbuilder) =>
            {
                // your default startup (of TestServer.Create)
                // register some custom stubs/mocks using ioc setup or owin middleware
            } );

Upvotes: 1

Related Questions