October 05, 2022 by Anuraj Estimated read time : 4 mins
This post is about how to add unit tests your azure functions. Like ASP.NET Core apps and Web APIs, we can add unit tests for Azure Functions as well. I am using Visual Studio and C#. I am creating the function in .NET as well. First I am creating an Azure Function using Visual Studio. I am modifying the existing function a little and the updated function looks like this.
In the function I am expecting a query string or element with key message and if it exists function returns it, if not, function return a BadRequest result. Next I am adding a XUnit Project to the solution. Then I am adding the a nuget package reference - Microsoft.AspNetCore.Mvc this is required for the unit test to interact with the azure function. And then add reference of the Azure Function as well to the unit test project. Now the unit test project looks like this.
Now let us write the unit tests. I am writing two unit tests for this function, one with input parameter and one without input parameter. Here are the unit tests.
Update : Based on the inputs from Sean Killeen, changed the unit test methods to async.
In the first test, I am creating HttpRequest with a query parameter collection. Then I am creating a logger instance - this is required since the Azure function is taking the logger as a parameter. Next I am invoking the Run static method of the function with the parameters. Since it is a async function, I am waiting for the execution to complete and then asserting whether it is OkayObjectResult class or not. Then validates the input and output as well. In the second one, I am not passing any parameter and verify the result. Now we can open the test explorer and execute the tests and view the results.
Here is the screenshot.
We can use the same technique for non static functions as well, where you configured Startup class and injecting dependencies through constructor. I wrote a blog post on this long back - How to add a Startup class to Azure Functions