How To Unit Test Your Hangfire Tasks

On most tutorials you come across that involve Hangfire, most will use a static Hangfire API.  Most tutorials also add tasks into Hangfire as static classes.  If you love TDD and you want to make your codebase as testable as possible, then read on.

Why You'll Need A Hangfire Wrapper

To unit test Hangfire, you will need to use the IBackgroundJobClient interface. If you use DI on your project and you try and inject it, it is very likely that you will get an error, like:

No default Instance is registered and cannot be automatically determined for type 'Hangfire.IBackgroundJobClient'

If you try to register IBackgroundJobClientin your DI you'll probably get this error:

No default Instance is registered and cannot be automatically determined for type 'Hangfire.JobStorage'

The fun starts here, as registering this with structure map looks like this:

            return new Container(c =>
            {
                c.For<IBackgroundJobClient>().Use<BackgroundJobClient>();
                c.For<JobStorage>().Use(JobStorage.Current);
            });

Which will result in this error:

JobStorage.Current property value has not been initialized. You must set it before using Hangfire Client or Server API.

Instead of banging your head on all these issues, writing a simple wrapper will make your life a lot easier.  The class will look like this:

 

      public class HangfireWrapper : IHangfireWrapper
    {
        public IBackgroundJobClient BackgroundJobClient => new BackgroundJobClient(JobStorage.Current);
    }

The interface looks like this:

    public interface IHangfireWrapper
    {
        IBackgroundJobClient BackgroundJobClient { get; }
    }

Testing Your Jobs

Now you have IBackgroundJobClient injected without a load of errors being thrown, you can start writing your scheduling code, like so:

public void MyMethod(IHangfireWrapper hangfireWrapper, IMyCode mycode)
{
     hangfireWrapper.BackgroundJobClient.Enqueue(() => _mycode.MyMethod());
}

Now, we have a fully testable method, we can write the following test to ensure that our code gets added into Hangfire:

        [Test]
        public void MyTest()
        {
            _mycode.MyMethod();
            _backgroundJobClient.Verify(x => x.Create(
                   It.Is(job => job.Method.Name == "MyMethod"),
                   It.IsAny()));
        }

You can now start writing tests against your code and improve your code coverage!

 

submit to reddit

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

Back to top