Unit testing Azure Functions
...and some SonarCloud code analysis!

Copenhagen based cloud developer. Love to code and to make complex solutions simple!
Search for a command to run...
...and some SonarCloud code analysis!

Copenhagen based cloud developer. Love to code and to make complex solutions simple!
Nice post 👍. Just so you know, you can now use the #azure-functions tag for your articles.
Thanks, Alexandre - great too see that tag added! 😀
This series will cover lots of practical and hard learned experiences developing Azure Functions. Read about how to design your microservice setup, how to implement the functions using triggers.
How to receive Twilio webhooks using Azure Functions There are a few ways to develop Azure Functions. In this post we are going to use Visual Studio to develop the function, but we could also have choosen to use the Azure Portal. Since I don't like t...
And examples for .NET projects also

...and why Windows is not going to sleep when left idle

TL;DR Keep trying the firmware update - after around 30 attempts doing the same thing, it just worked 🤯🎉🪅 Awesome Ultrawide Monitor, not only for gaming For once I'm going to write an article which is not directly related to programming, but if yo...

When using GitHub actions it's pretty neat that you can use the hosted GitHub runners. However, this can get costly if you use a lot of runners and they are not always that fast at running the actions. Luckily you can also host your own runners and w...

We all want to find these little bugs before they cause too much trouble!
When working with Azure Functions in real world scenarios it can sometime be a pain to run them. The reason for this is that with micro services like Azure Functions they almost always exist in a complex setup with lots of different moving parts and you often don't have full control over when they are executed, etc. That's one of the reasons why it's a good idea to write some unit tests when you develop your functions. There are of course a lot of other good reasons for writing unit tests, but you know that already 😎
You can also run your functions locally, which you should also do, here's how to do that
Before we dig in....
It's a personal choice and there's no right answer. I prefer xUnit because you can use [Fact] and inject test data via attributes with [InlineData], [ClassData], and [MemberData].
We are going to start writing the unit test for our function, that way we can brag about doing Test Driven Development (and it actually makes pretty good sense as a bonus 😁) Simply launch Visual Studio, create a new unit test project, select your test framework of choice, if you're going to use my samples you need to select xUnit:

In the new test project add the Moq Nuget:
install-package Moq
In the following code we are going to:
[Theory]
[InlineData("", typeof(BadRequestResult))]
[InlineData("QueryParamValue", typeof(OkResult))]
[InlineData("ThisStringCausesTheFunctionToThrowAnError", typeof(InternalServerErrorResult))]
public async Task Function_Returns_Correct_StatusCode(string queryParam, Type expectedResult)
{
//Arrange
var qc = new QueryCollection(new Dictionary<string, StringValues>{{"q", new StringValues(queryParam)}});
var request = new Mock<HttpRequest>();
request.Setup(x => x.Query)
.Returns(() => qc);
var logger = Mock.Of<ILogger>();
//Act
var response = await Function1.Run(request.Object, logger);
//Assert
Assert.True(response.GetType() == expectedResult);
}
When doing TTD we will have compilation errors at this point, obviously because we haven't added the function yet.
Now add a new Azure Functions project, select Http trigger:

Replace the code in the class Function1.cs with this:
public static class Function1
{
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string queryParameter = req.Query["q"];
if (string.IsNullOrEmpty(queryParameter))
return new BadRequestResult();
if (queryParameter == "ThisStringCausesTheFunctionToThrowAnError")
return new InternalServerErrorResult();
return new OkResult();
}
}
You will notice that the QueryCollection that we mocked in the unit test are used in the HttpRequest passed to this function. It should be pretty obvious what happens here, we just do simple string comparison to be able to return different Http results that our tests can do assertions on.
Now build you projects and things should compile.
Remember the [InlineData] attributes we had in our test method? We are using those to parameterize the test so we can have multiple test cases in one test method. When we run our tests in VS, here's how it should look:

...you will notice one test run per [InlineData] attribute.
That's it for our simple unit test of Azure Functions. I know a lot of people are using Dependency Injection in Azure Functions (my self included) and if that's the case you will have to make some modifications to this, let me know in the comments if you're interested in a blob post about that.
I have added this sample project to my sonarcloud.io account since I'm really starting to use that a lot for many project and I really like the features they have and how easy it is to improve code quality with a tool like SonarCloud.
So for this little project, here's how the SonarCloud analysis looks:

Stay tuned for a post on how to configure GitHub actions to trigger a SonarCloud analysis and get your source code analysed.
That's all, as always you can find the relevant source code on my Github, here's the repo