Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Custom Factory Middleware

I am creating an asp.net core web app, which creates routes from user defined sources (config, database etc). I have used a middleware factory based approach which works fine, except I do not know how to isolate a middleware for unit/integration testing. I use the route data from the HttpContext to validate the incoming request against the user defined configuration source, so I need the HttpContext to have RouteData, which is why I am leaning towards Integration testing with xUnit.

If I make a request using a httpclient created via AspNetCore.TestHost.TestServer.CreateCLient(), I work my way through my entire call chain, which is what I expect. What I need to be able to do is terminate the middleware or provide the HttpContext with RouteData.

I have tried an ugly unit test using AutoFixture and the DefaultHttpContext(), but as expected, I don't get any RouteData on my HttpContext, so my tests can never pass.

Middleware

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
     try 
     {
         if (_flowApis.Count == 0)
              throw new ArgumentNullException();

          var doesMatch = false;
          var routeData = context.GetRouteData();

          foreach (var api in _flowApis)
          {
             if (!RequestType.IsValidRequestType(api.Request.Type))
                  throw new InvalidOperationException();
             else
                 foreach (Route route in routeData.Routers.Where(r => r.GetType() == typeof(Route)))
                 {
                     if (route.RouteTemplate == api.Route)
                     {
                        if (route.Constraints.TryGetValue("httpMethod", out IRouteConstraint routeConstraint))
                        {
                             var value = (HttpMethodRouteConstraint)routeConstraint;
                             if (value.AllowedMethods.Contains(api.Method))
                             {
                                 doesMatch = true;
                                 var routeValues = GetRouteValues(routeData);
                                 var request = new Core.Request(context.Request, api, routeValues);
                                        context.Items.Add(nameof(Core.Request), request);
                                        break;
                                    }
                                }
                            }
                        }
                    if (doesMatch)
                        break;
                }

                if (!doesMatch)
                {
                    context.Response.StatusCode = 404;
                    await context.Response.WriteAsync("", new CancellationToken());
                }
                else
                    await next(context);
            }
            catch(ArgumentNullException ex)
            {
                var mex = new MiddleWareException<MatchRouteToFlowApiMiddleware>("Flow Configuration in app.settings has not been set.", ex);
                context.Response.StatusCode = 500;
                await context.Response.WriteAsync("", new CancellationToken());
            }
            catch (InvalidOperationException ex)
            {
                var mex = new MiddleWareException<MatchRouteToFlowApiMiddleware>("Invalid Request Type", ex);
                context.Response.StatusCode = 500;
                await context.Response.WriteAsync("", new CancellationToken());
            }
        }

Unit Test

[TestMethod]
public async Task Request_path_matches_an_api_route_and_method()
{
var fixture = ScaffoldFixture();
var flowApi = fixture.Build<FlowApi>()
                     .With(p => p.Route, "/some/path")
                     .With(m => m.Method, "GET")
                     .Create();
var flowApiRequest = fixture.Build<Request>()
                            .With(t => t.Type, "CData")
                            .Create();
flowApi.Request = flowApiRequest;
var flowConfiguration = fixture.Create<FlowConfiguration>();
flowConfiguration.FlowApis.Clear();
flowConfiguration.FlowApis.Add(flowApi);

var middleware = new MatchRouteToFlowApiMiddleware(flowConfiguration: flowConfiguration);
var context = new DefaultHttpContext();
context.Request.Method = "GET";
context.Request.Path = "/some/path";
context.Response.Body = new MemoryStream();

await middleware.InvokeAsync(context, (httpContext) => Task.FromResult(0));

context.Items.ContainsKey(nameof(Core.Request)).Should().BeTrue();
}

Integration test


[Fact]
public async Task Request_path_matches_an_api_route_and_method()
{
            //Arrange
   var response = await _httpClient.GetAsync("/some/route");

   response.StatusCode.Should().Be(500);
}

When executing the unit test, I can never satisfy the inner for each beacuse I don't have route data on the HttpContext.

When executing the integration test, the middleware executes as expected but since it does not terminate, i cannot validate

like image 562
SamV Avatar asked Jun 14 '26 23:06

SamV


1 Answers

I realised that trying to terminate my middleware just to validate it using xUnit meant I would not be testing my system as is, so I looked more at my unit test setup.

I have managed to get Route Data on the HttpContext. It feels messy but is a starting point at least.

 private static DefaultHttpContext DefaultHttpContextWithRoute(Fixture fixture)
 {
     var context = new DefaultHttpContext();
     var routeDictionary = new RouteValueDictionary
     {
         { "some","path" }
     };
     context.Features.Set<IRoutingFeature>(new RoutingFeature());
     context.Features.Get<IRoutingFeature>().RouteData = new RouteData(routeDictionary);

     var inline = fixture.Create<DefaultInlineConstraintResolver>();
     var route = new Route(new TestRouter(), "/some/path", inline);
     var httpMethodRouteConstraint = new HttpMethodRouteConstraint("GET");
     route.Constraints.Add("httpMethod", httpMethodRouteConstraint);
     context.Features.Get<IRoutingFeature>().RouteData.Routers.Add(route);
     context.Request.Method = "GET";
     context.Request.Path = "/some/path";
     context.Response.Body = new MemoryStream();
     return context;
}

private class TestRouter : IRouter
{
     public VirtualPathData GetVirtualPath(VirtualPathContext context)
     {
         throw new NotImplementedException();
     }

     public Task RouteAsync(RouteContext context)
     {
                throw new NotImplementedException();
     }
}

In each unit test I call the DefaultHttpContext and use invoke my middleware like so

DefaultHttpContext context = DefaultHttpContextWithRoute(fixture);

await middleware.InvokeAsync(context, (httpContext) => Task.FromResult(0));
like image 98
SamV Avatar answered Jun 16 '26 14:06

SamV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!