'Hangfire Not Getting Configurations when I try to run Test Case for the method containing hangfire activation .net Core REST Web API

  public async Task<IActionResult> SendOrders()
    {
        try
        {
            RecurringJob.AddOrUpdate("powerfuljob", () => _lab.SendOrders("QUEST DIAGNOSTIC"), "*/1 * * * *");
        }
    }

Above is the method written in a controller that i want to test using xUnit

  [Fact]
  public async Task LabControllerTestCase_SendOrders()
    {
        var okResult = await _Labcontroller.SendOrders();
        Assert.IsType<OkObjectResult>(okResult as OkObjectResult);
    }

When Ever I try to Run the given Test Case it gives the following exception

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

Hangfire is working fine when I try to run the solution but when i try to test it using xUnit test case it gives the mentioned exception.

According to my findings the issue is because it does't run Startup file so it can't activate the hangfire job or it can't find any hangfire service.

Your remarks will be valuable.

Thanks



Solution 1:[1]

I got rid of this error with the following solution:

 IServiceCollection services = new ServiceCollection();

 services.AddHangfire(configuration => configuration
             .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
             .UseSimpleAssemblyNameTypeSerializer()
             .UseRecommendedSerializerSettings()
             .UseSqlServerStorage(_configuration.GetConnectionString("ConnStringHF"),
 new SqlServerStorageOptions
             {
                 CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
                 SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
                 QueuePollInterval = TimeSpan.Zero,
                 UseRecommendedIsolationLevel = true,
                 DisableGlobalLocks = true
             }));

 JobStorage.Current = new
 SqlServerStorage(_configuration.GetConnectionString("ConnStringHF"));

 services.AddHangfireServer();

I hope this might help someone like me who was stuck in it for about a week while writing test cases.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tom