0

Don't get me wrong! This question has been asked here before but it didn't get any answer (that works) or it also does not similar to my.

I have a ASP.net Web API running .net 4.5 that use Hangfire v1.7.2

In Startup.cs I have:

public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);

            GlobalConfiguration.Configuration.UseSqlServerStorage("myDbConnString");
            app.UseHangfireDashboard("/hangfire", new DashboardOptions()
            {
                Authorization = new[] { new HangfireAuthorizationFilter() }
            });

            app.UseHangfireServer();
        }

In MyController.cs I have Hangfire enque a job that execute DoSomething()

public async Task<IHttpActionResult> PostPerson(Person p)
{      
    // spin up a new dedicated thread and execut the job
    BackgroundJob.Enqueue(() => DoSomething(p.Id));

    return OK;
}

If I test with Postman tool trying to call the my web API HTTPPost method I see my code execute nicely and everything good.

However, when I am using NUnit Test V3 to unit-test the MyController.cs I am having an issue when hitting this line in the controller BackgroundJob.Enqueue(() => DoSomething(p.Id));

[Test]
public void Post()
{
     MyController controller = new MyController();
     Person p = new Person
     {
         data = "hello world"
     };

     var actionResult = controller.PostPerson(p);
}

Stack trace:

at Hangfire.JobStorage.get_Current() at Hangfire.BackgroundJob.<>c.<.cctor>b__45_0() at System.Lazy1.CreateValue() at System.Lazy1.LazyInitValue() at Hangfire.BackgroundJob.Enqueue(Expression`1 methodCall) at myApp.Controllers.MyController.d__3.MoveNext()

Error msg:

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

Please help me with what is the issue here and how to fix it.

Thank you!

CB4
  • 690
  • 3
  • 13
  • 25
  • Tightly coupled to implementation concerns make it difficult to unit test in isolation. Encapsulate the `BackgroundJob.Enqueue` behind an abstraction so you can test your controller in isolation with out knock on effect of hangfire – Nkosi May 12 '19 at 21:49
  • @Nkosi can you elaborate with some code? I have been following this `https://docs.hangfire.io/en/latest/background-methods/writing-unit-tests.html` but it just lead to many other error. – CB4 May 13 '19 at 18:45
  • @CB4 have you found an answer to your questions yet? – hbulens Oct 08 '19 at 17:58

0 Answers0