Photo by Sieuwert Otterloo

Unit test multipart requests in your C# Azure Functions

Mock your multipart request easily!

Posted by Damien Aicheh on 02/10/2022 · 6 mins

When you create an Azure Functions HTTP trigger you sometimes needs to send files using multipart requests. But how to unit test this? That’s what we will discover in this tutorial.

Basic example

Let’s assume we have an Azure Function that receive data in multiparts. We have two types of data in this example: json and a file.

The code will looks like this:

public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req)
{
    var reqFormData = await req.ReadFormAsync();

    string data = reqFormData["data"];
    if (data == null)
    {
        return new BadRequestObjectResult(Errors.DATA_NOT_PROVIDED);
    }

    var file = reqFormData.Files["myFile"];
    if (file == null)
    {
        return new BadRequestObjectResult(Errors.FILE_NOT_PROVIDED);
    }

    // Do whatever you want with the data and files...

    return new OkObjectResult("This HTTP triggered function executed successfully.");
}

As you can see we read the informations from the request form and then we are able to check if the datas are correct or not and then use it after in the Azure Function.

That being said, how to test this Run function?

Mock the multipart request

The key point here is how to be able to mock the Http request and return the multipart data we want. To achieve this we will create an HttpHelper class and add two methods:

  • One to create the multipart request that we will call CreateMultipartRequest
  • The other one will be responsible of creating the file for the multipart request and will be called CreateFormFile
public static DefaultHttpRequest CreateMultipartRequest(FormCollection formCollection)
{
    var request = new DefaultHttpRequest(new DefaultHttpContext())
    {
        Method = "POST",
        ContentType = "multipart/form-data",
        Form = formCollection,
    };

    return request;
}

The method above takes a FormCollection which will contain the json and file for your request. The second below will simulate a file for your multipart request.

public static IFormFile CreateFormFile(string keyname, string filePath, string contentType)
{
    using (var stream = File.OpenRead(filePath))
        return new FormFile(stream, 0, stream.Length, keyname, filePath)
        {
            Headers = new HeaderDictionary(),
            ContentType = contentType
        };
}

With that ready let’s see it in action!

Unit Tests

In the example of code below we can now test if our json data and file trigger the correct methods of our Azure Function endpoint.

[Fact]
public async Task TestRun_AllDataProvidedCorrectly_ReturnOkObjectResult()
{
    // Arrange
    var formFileCollection = new FormFileCollection();
    formFileCollection.Add(HttpHelper.CreateFormFile("myFile", "Assets/demo.png", "image/png"));

    var formCollection = new FormCollection(new Dictionary<string, Microsoft.Extensions.Primitives.StringValues>()
    {
        { "data", "My data" },
    }, formFileCollection);
    var request = HttpHelper.CreateMultipartRequest(formCollection);

    // Act
    var result = (ObjectResult)await _sut.Run(request);

    // Assert
    Assert.NotNull(result);
    Assert.IsType<OkObjectResult>(result);
    Assert.Equal(result.StatusCode, 200);
}

In the Arrange section we create the multipart request for an image called demo.png which is available in an Assets folder of our project. Don’t forget to declare it as an EmbeddedResource in your csproj like this:

<ItemGroup>
  <EmbeddedResource Include="Assets\demo.png">
    <CopyToOutputDirectory>Always</CopyToOutputDirectory>
  </EmbeddedResource>
</ItemGroup>

Then we create a FormCollection object and add the image as a FormFile to the request.

Then in the Act section we can launch the request and in the Assert one we check the result we expect.

Final touch

Now you know how to unit tests multipart requests of your Azure Functions. Of course, you can improve the helper methods with your own use cases. You will find an entire example in this Github repository with multiples unit tests.

Happy coding!

You liked this tutorial? Leave a star in the associated Github repository!

Do not hesitate to follow me on to not miss my next tutorial!