简体   繁体   中英

Integration testing ASP.NET Web API 2 using HttpServer/HttpClient; no HttpContext

I'm looking to integration test a web service built on ASP.NET Web API 2. Many things such as cookies, getting the current principal, etc. are done through HttpContext.Current.

I found the following resource on integration testing ASP.NET: http://amy.palamounta.in/blog/2013/08/04/integration-testing-for-asp-dot-net-web-api/

This works great. It spins up an in-memory host and combined with the automated schema generation of Entity Framework 6, setup and teardown are easy.

The problem comes in when things try and use HttpContext.Current to, as aforementioned, get cookies/etc. It seems that when hosting in-memory using HttpServer, HttpContext.Current is always null. This does make a little sense given there's no real request, but is a pain - it means the integration tests can't cover anything requiring anything from this property.

What can I do here? It looks like very little of the data I'm using is present anywhere but HttpContext.Current, so am I just going to have to spin up full external instances on IIS?

In order to test your api using self host you have to avoid calling HttpContext.Current from a web api context. You can wrap it in something you can mock, like so:

public static class CurrentHttpContext
{
    public static Func<HttpContextBase> Instance = () => new HttpContextWrapper(HttpContext.Current);
}

Then when you are creating your test server you could set the CurrentHttpContext to some fake HttpContextBase . For example using FakeItEasy ( http://fakeiteasy.github.io/ ):

var context = A.Fake<HttpContextBase>();
CurrentHttpContext.Instance = () => context;

And then use this anywhere you need to access HttpContext :

var context = CurrentHttpContext.Instance();
// do what you need to do to httpcontext now like setting principal, cookies etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM