I have ASP.NET MVC5 and WebApi2 application with some MVC and ApiControllers. OWIN and Autofac is used. I wrote Integration test which calls some web api method and tests a response:
[TestMethod]
public async Task GetUsersForTreeTest()
{
using (var server = TestServer.Create<Startup>())
using (var client = new HttpClient(server.Handler))
{
client.BaseAddress = new Uri("http://localhost/api/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var resp = await client.GetAsync("User/GetUsersForTree");
resp.EnsureSuccessStatusCode();
var users = await resp.Content.ReadAsAsync<List<UserForTreeDto>>();
Assert.IsTrue(users.Any());
}
}
Startup is my OWIN startup class. I initialize dependency resolvers for MVC and WebApi with Autofac inside.
When I run the test I get an exception:
System.ArgumentNullException: Value cannot be null. Parameter name: httpContext Result StackTrace: at System.Web.HttpContextWrapper..ctor(HttpContext httpContext) at Owin.AutofacMvcAppBuilderExtensions.<>c.<.cctor>b__2_0() at Owin.AutofacMvcAppBuilderExtensions.<>c.<b__1_0>d.MoveNext()
But when I comment
app.UseAutofacMvc();
the test passed. As I understand, error happes in this line of AutofacMvcAppBuilderExtensions class.
Looks like HttpContext.Current is null.
How can I initialize HttpContext?