In this tutorial, you will learn how to unit test your hangfire scheduled jobs. Most online tutorials that involve Hangfire, use the static Hangfire API to schedule jobs. Most tutorials also add jobs into the Hangfire queue using static classes. If you love TDD and you want to make your codebase as testable as possible, then read on. For this tutorial, I will use StructureMap as the IoC container!
Why You'll Need A Hangfire Wrapper
To unit test Hangfire, you will need to use the
IBackgroundJobClient interface. If you use dependency injection within your project and you try and inject
IBackgroundJobClient without performing any additional configuration, it is very likely that you will get several errors, one being:
No default Instance is registered and cannot be automatically determined for type 'Hangfire.JobStorage'
If you think that simply registering this dependency within the projects inversion of the control container will solve your problems you may be in for a shock. Registering a dependency within StructureMap looks like this:
After successfully registering
IBackgroundJobClient, you will bump in this error:
JobStorage.The current property value has not been initialized. You must set it before using Hangfire Client or Server API.
As you can see trying to get Hangfire to work with IoC is a pain. Instead of banging your head trying to get it to work, a simpler solution is to create a simple wrapper around Hangfire that will make your life a lot easier. The code to create this wrapper should look like this:
The interface for the wrapper will look like this:
With these things set up you can access Hangfire into your classes, avoiding using a static class. You should be able to inject
IBackgroundJobClient without a load of errors being thrown. This will allow you to test your code!!!!
Testing Your Jobs
An example of the code required to write a scheduled job is shown below:
This is a fully unit-testable method. As this code is now testable, we can write the following test to ensure that our code gets added into Hangfire correctly:
You can now start writing tests against your code and improve your code coverage! Happy Coding 🤘