Taf Munyurwa
Taf Munyurwa

Reputation: 1572

How do I mock the HttpRequest on an "azure function"

I have a function with an Http trigger

public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function,"post", Route = null)] HttpRequest req)

I want to mock the req. I have manage to do so just fine like this

private static Mock<HttpRequest> CreateMockRequest(object body)
{            
    using var memoryStream= new MemoryStream();
    using var writer = new StreamWriter(memoryStream);
 
    var json = JsonConvert.SerializeObject(body);
 
    writer .Write(json);
    writer .Flush();
 
    memoryStream.Position = 0;
 
    var mockRequest = new Mock<HttpRequest>();
    mockRequest.Setup(x => x.Body).Returns(memoryStream);
    mockRequest.Setup(x => x.ContentType).Returns("application/json");

    return mockRequest;
}

body, in the above code is just some json. I am then using this code to deserialize this the json stuffed in the body of the mockRequest

public static async Task<HttpResponseBody<T>> GetBodyAsync<T>(this HttpRequest req)
    using var stream = new StreamReader(req.Body);
    var bodyString = await stream.ReadToEndAsync();
...
}

The bodyString is not valid json here because there seems to be escaping of the quotes in the json e.g. Original Json = {"x": "somexvalue"} the value coming back = {\"x\": \"somexvalue\"

Before you say that this is just visual studio debug inspector, it is not. I have checked. It seems the StreamWriter is doing this or the StreamReader is.

The obvious solution was to just strip the \ out of the resulting json but this feels so wrong and work arroundy. Is there a way to fix this without having to change my function.

Upvotes: 6

Views: 7376

Answers (1)

Taf Munyurwa
Taf Munyurwa

Reputation: 1572

So, the issue is with the StreamWritter. The way around it is just to not use the StreamWritter. @ColinM was on the right line. This is the way to mock the body

    var json = JsonConvert.SerializeObject(body);

    var memoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));

    var context = new DefaultHttpContext();
    var request = context.Request;
    request.Body = memoryStream;
    request.ContentType = "application/json";

    return request;

Upvotes: 5

Related Questions