Cedric Dumont
Cedric Dumont

Reputation: 1029

Testing asp.net 5 vnext middleware from a TestServer

In owin, its possible to test a web api in unit test using a TestServer (see this blog).

Is this functionality available for asp.net 5 middleware ?

UPDATE:

based on responses below, I tried to use TestServer, but visual studio complains that 'The type or namespace name 'AspNet' does not exist in the namespace 'Microsoft' (are you .....'

Upvotes: 5

Views: 1842

Answers (1)

tugberk
tugberk

Reputation: 58454

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

Here is a sample. 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 find more about the usage of the TestServer class on the tests.

Upvotes: 11

Related Questions