Create Unit Test for MVC 5 with Owin

I am trying to create a unit test to run with the controllers that are included in the .NET template project for MVC 5 in Visual Studio 2013 using Framework 4.5.1.

It was supposed to test the ManageController class included in the project for standard user login.

Here is the code that I use to invoke the controller index action (remember that the Index action is standard):

[TestClass] public class ManageControllerTests { [TestMethod] public async Task ManageController_Index_ShoudlPass() { using (var server = TestServer.Create<Startup>()) { var response = await server.HttpClient.GetAsync("/Manage"); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } } } 

The test is not interrupted, but the answer is 404. And if I try to debug the process, it does not seem to fall into the Index method in the controller or controller constructor event.

I added the Microsoft.Owin.Testing package through NuGet. And the configuration method in the application launch class is called correctly.

What am I missing? I could not find a clear example on the Internet to implement this test. Can someone step by step put here how to test this controller?

thanks

+7
unit-testing asp.net-mvc-5 owin
source share
1 answer

You cannot do this. The OWIN pipeline is designed for decoupling from any hosting env.

MVC is heavily system.web with system.web , which makes testing with the OWIN pipeline difficult.

You can do something like this:

 [TestClass] public class ManageControllerTests { [TestMethod] public async Task ManageController_Index_ShoudlPass() { using (var server = CustomTestServer.Create<Startup>()) { server.OnNextMiddleware = context => { context.Response.StatusCode.ShouldBe(Convert.ToInt16(HttpStatusCode.OK)); return Task.FromResult(0); } var response = await server.HttpClient.GetAsync("/Manage"); } } 

You will need to withdraw

  public class CustomTestServer : TestServer 

And add the middleware to the constructor after the existing middleware

 appBuilder.Use(async (context, next) => { await OnNextMiddleware(context); }); 

And a public member

public Func<IOwinContext, Task> OnNextMiddleware { get; set; }

From there, when you call server.httpclient.getasync... , the middleware will pass the response to the next middleware for processing.

+1
source share

All Articles