Unit Testing your Azure Functions

You know ... I told myself to stay away from pre-releases and only stick to released software from now on. Well, I failed. Having great experiences from Azure Web Jobs, which I've written about before, I just had to get my hands on the new Visual Studio tooling for Azure Functions, where you use the same tried and true attributes on your method arguments to bind to external resources as you've been accustomed to.



Intellisense is awesome. Visual Studio is awesome. I'm really liking Microsoft these days! Now, one thing that was missing from any guidance that I could get my hands on, were how to properly test your functions. There are guides on how to write code and use tools to call your actual functions in a host, but I couldn't readily find anything that told me how to test them quickly in isolation. Here's what I did:

I created a new Unit Test Project, installed ...



... and ended up creating two constructs that turned out to be helpful: The Verbose Diagnostics Trace Writer and the abstract Function Test class.



Not much to it - what gets logged, gets written to any Debug.Listeners, which defaults to your output window.



Here, there's a bit more going on: The helper method creates a HttpRequestMessage of Post (I found that it didn't matter / wasn't validated in by the runtime in a test context). It sets the request uri to an arbitrary identifier, maps the application route to the system temp folder and then serializes any object content passed in as JSON. Finally, it creates an instance of our verbose logger and returns that, together with the request.

As you can see, I've made a fair bit of assumptions. But then, I'm only here to spread ideas ;-). With the above infrastructure, I was able to create neat unit tests like those below:



Why functions?

Web Jobs have treated me well. However, they fall short when it comes to dependency isolation. Since Web Jobs are deployed together with their web site, all web jobs must use compatible NuGet packages for things to work smoothly. The least intrusive way of doing this, I've found, is to put them all in the same Visual Studio solution. This is something I've never liked. I want to be able to quickly load a specific set of code resources to solve a specific task (think single-responsibility). I don't want to load up an entire system, but rather a part of it - a functional piece; a microservice (if you are so inclined). Function apps let me do just that.

Comments

Popular posts from this blog

Auto Mapper and Record Types - will they blend?

Unit testing your Azure functions - part 2: Queues and Blobs

Testing WCF services with user credentials and binary endpoints