Testing asp.net 5 vnext middleware from TestServer

In owin, you can test the web api in unit test using TestServer (see this blog ).

Is this functionality available for asp.net 5 middleware?

UPDATE:

based on the answers below, I tried using TestServer, but visual studio complains that the "Type or namespace name" AspNet "does not exist in the namespace" Microsoft "(you ..... '

  • I am using Visual Studio 2015

  • in my sources (settings) I have ( https://www.myget.org/F/aspnetmaster/ ) (I also tried with https://www.myget.org/F/aspnetvnext/ , but got the same problem )

  • here is my project.json file

    { "version": "1.0.0-*", "dependencies": { "Microsoft.AspNet.Http": "1.0.0-*", "Microsoft.AspNet.TestHost": "1.0.0-*", "Microsoft.AspNet.Hosting": "1.0.0-*", "Microsoft.AspNet.Testing" : "1.0.0-*", "xunit": "2.1.0-beta1-*", "xunit.runner.aspnet": "2.1.0-beta1-*", "Moq": "4.2.1312.1622", "Shouldly": "2.4.0" }, "commands": { "test": "xunit.runner.aspnet" }, "frameworks" : { "aspnet50" : { "dependencies": { } } } } 
+5
source share
1 answer

It is also available on ASP.NET 5: Microsoft.AspNet.TestHost .

Here is an example. Middleware:

 public class DummyMiddleware { private readonly RequestDelegate _next; public DummyMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { Console.WriteLine("DummyMiddleware"); context.Response.ContentType = "text/html"; context.Response.StatusCode = 200; await context.Response.WriteAsync("hello world"); } } 

Test:

 [Fact] public async Task Should_give_200_Response() { var server = TestServer.Create((app) => { app.UseMiddleware<DummyMiddleware>(); }); using(server) { var response = await server.CreateClient().GetAsync("/"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } 

You can learn more about using the TestServer class in tests .

+11
source

All Articles