Search code examples
unit-testing.net-coreintegration-testingxunit

How to mock a web api for testing


I have a class library which is included some DelegationHandlers, It is simple, get the request, add some headers based on request content and pass the request down.

So what I needed is write unit tests for my library. I'm using .NET Core 2.1 and xunit, I was wondering if there is a way to mock a web server, then I can send a request to this web server using my library and check the result of my request? Any Idea how could I mock a web server (app)? or how could I test my library by sending a http request?


Solution

  • I found a solution here, I share it maybe useful for others.

    public void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, RequestDelegate del)
    {
        _builder = new WebHostBuilder()
            .UseUrls(baseUrl)
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .Configure(app =>
            {
                app.UsePathBase(basePath);
                app.Run(del);
            })
            .Build();
    
        _builder.Start();
    }
    

    The same WebHostBuilder we used in Integration Tests, now we could pass RequestDelegate to run the app:

    GivenThereIsAServiceRunningOn(baseUrl, basePath, async context =>
    {
        _downstreamPath = !string.IsNullOrEmpty(context.Request.PathBase.Value) ? context.Request.PathBase.Value : context.Request.Path.Value;
    
        if (_downstreamPath != basePath)
        {
            context.Response.StatusCode = statusCode;
            await context.Response.WriteAsync("downstream path didn't match base path");
        }
        else
        {
            context.Response.StatusCode = statusCode;
            await context.Response.WriteAsync(responseBody);
        }
    });