How to use Hangfire.MemoryStorage in unit tests and jobs actually getting scheduled?

I would like to write a integration test were I can verify that a job gets automatically retried when it’s failing. Recently, I am wondering how I can setup a test in such way the scheduler is actually working? Can I somehow get informed whether the job I Enqueued actually got processed?

Currently, I am having the below code for the test but it’s not working for me:

       var jobStorage = new MemoryStorage();
       var options = new BackgroundJobServerOptions();
       GlobalConfiguration.Configuration.UseStorage(jobStorage);

        // Start
        var scheduler = new BackgroundJobServer(options);
        // add my custom AutomaticRetry job filter instance to global job filters collection
        ApplySchedulerConfiguration(); 

        BackgroundJob.Enqueue<JobTask>(task => task.ExecuteJob(123456, null));

        // Stop
        scheduler.Dispose();

Only how can I verify that a job got rescheduled multiple times to ensure the automatic retry is working and is enabled in our project?

Anyone having any idea how to accomplish this?

I’ve wrote integration tests using hangfire and sql server and you typically want to call Storage.Current.GetConnection().GetJobData() to confirm state transitions and GetJobParameter for the retry counter (parameter “RetryCount”, see https://github.com/HangfireIO/Hangfire/blob/master/src/Hangfire.Core/AutomaticRetryAttribute.cs#L198).

You’ll probably want to put your test into a loop waiting for the state you expect it to eventually be in, and Polly is a great library for doing something like this with timeouts.

Yes, I have seen the tests for AutomaticRetryAttribute but I am not following you how I can use put my test in a loop waiting for the state I am expecting to be. Basically, I want to ensure the RetryCount parameter of the job is at least higher then 3-4.

How would Polly work with this? Maybe I need to schedule a job and store the returned job id then within Polly query the job data? JobData should then have the Job instance and I think I can dig up the job parameters from there.

Yeah just call the apis to get the job data, but you can then wrap it on a polly retry if the result isn’t the one you expect.

Then you can wrap it in a polly timeout to give up after a cetain period of time (probably want to make this a pessimistic timeout because I don’t think these hangfire apis take cancellation tokens).