Unit test middleware Azure Functions isolated

Viewed 91

I've created a simple Azure Functions app (isolated model). It is just the standard code you get when starting up the project to which I've added a middleware class. With help of a stackoverflow post I was able to unit test my "Hello world" function.

I'm now however having problems with unit testing the middleware class:

public class AuthenticationMiddleware : IFunctionsWorkerMiddleware
{
    public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
    {
        string headers = context.BindingContext.BindingData["Headers"]?.ToString();
        var httpHeaders = headers == null ? null : System.Text.Json.JsonSerializer.Deserialize<HttpHeaders>(headers);

        if (httpHeaders.Authorization == "foo")
            await next(context);
        else
        {
            var request = await context.GetHttpRequestDataAsync();
            var response = request.CreateResponse(HttpStatusCode.Unauthorized);
            await response.WriteAsJsonAsync(new { Message = "Token is not valid." });
            context.SetResponseData(response);
        }
    }    
}

public class AuthenticationMiddlewareTests
{
    [Fact()]
    public async Task Invoke_WithInvalidAuthorizationHeader_FunctionContextHasUnauthorizedResponseCodeAndJsonResponse()
    {
        // Arrange
        var functionDefinition = new MockFunctionDefinition(new Dictionary<string, BindingMetadata>() { { "req", new MockBindingMetadata() } });
        var context = new MockFunctionContext(functionDefinition);
        FunctionExecutionDelegate functionExecutionDel = async (context) => await Task.FromResult(context);
     
        var middleWare = new AuthenticationMiddleware();

        // Act
        await middleWare.Invoke(context, functionExecutionDel);

        // Assert

        // extract response data from context... to do ('act' part throws exception, first fix that)
    }
}

(for unit testing this class I used separate mocking classes because mocking everything in the test class itself, like I did for the function, became kind of messy)

I'm getting a NullReferenceException from the 'GetHttpRequestDataAsync' extension method (which has been recently added to the azure-functions-dotnet-worker). If I uncheck "Enable Just My Code" in the Debugger options, then I see that this exception comes from the "InnerInvoke()" method, which throws an:

**System.AccessViolationException**: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

How can I solve this?

0 Answers
Related