Azure Functions has recently added a new feature that allows precompiled assembly to run functions. This gives us a great confidence with regards to unit testing. In this post, we are walking through how to unit test functions with ease, like which we do tests everyday.
The sample code used in this post can be found at HERE.
Function without Dependency
We’re not digging down precompiled function too much as it’s on the document. Let’s have a quick look at the HTTP trigger function code:
Nothing special. Now, we’re writing a test code for this function using xUnit and FluentAssertions.
How does it look like? It’s the same unit test code as what we do everyday. Let’s move on.
Function with Dependency
As I wrote Managing Dependencies in Azure Functions on the other day, dependency management is a bit tricky for Azure Functions due to its static
nature. Therefore, we should introduce Service Locator Pattern for dependency management (or injection). Here’s the sample function code:
As we can see the code above, value
is retrieved from the service locator instance. Of course, this is just a simple implementation of service locator pattern (If we need more sophisticated one, we should consider an IoC container library like Autofac). And here’s the poorman’s service locator:
Let’s see the test code for the function with dependencies. With the service locator, we can inject mocked object for unit testing, which is convenient for developers. In order for mocking, we use Moq in the following test code.
We create a mocked instance and inject it into the service locator. Then the injected value (or instance) is consumed within the function. How different is it from the everyday testing? There’s no difference at all. In other words, implementing a service locator gives us the same development experiences on Azure Functions, from the testing point of view.
I wrote another article for testing a few months ago, using ScriptCs. This used to be one approach, when Azure Functions didn’t support the precompiled assemblies. Now, we have precompiled functions supported. Therefore, I hope this post would be useful to design functions with better testability.