How to use xunit to unit test contains the function of hangfire

1.7k Views Asked by At

The develop language is dotnet core 3.0. I dont't have idea.Help Me!Thanks a lot.

The function like below :

function test(){
       BackgroundJob.Schedule<TradeCenterService>((s) => s.HandleSettlementJob(recordId), TimeSpan.FromSeconds(60));
}

I have config the hanfire in test class,like this

[DependsOn(typeof (AbpHangfireModule))]
public class MyProjectWebModule : AbpModule
{
    public override void PreInitialize()
    {
        Configuration.BackgroundJobs.UseHangfire();

    }

    //...
}

Now the test result error message is :

 System.InvalidOperationException : JobStorage.Current property value has not been initialized. You must set it before using Hangfire Client or Server API.
  堆栈跟踪: 
    JobStorage.get_Current()
    BackgroundJobClient.ctor()
    <.cctor>b__45_0()
    Lazy`1.PublicationOnlyViaFactory(LazyHelper initializer)
    Lazy`1.CreateValue()
    Lazy`1.get_Value()
1

There are 1 best solutions below

1
On

On the Hangfire's documentation page you have an example on how to write unit tests for the methods that depends on Hangfire. It's important to highlight that you still need to mock it. Using Moq, it would be something like: new Mock<IBackgroundJobClient>();

[TestMethod]
public void CheckForSpamJob_ShouldBeEnqueued()
{
    // Arrange
    var client = new Mock<IBackgroundJobClient>();
    var controller = new HomeController(client.Object);
    var comment = CreateComment();

    // Act
    controller.Create(comment);

    // Assert
    client.Verify(x => x.Create(
        It.Is<Job>(job => job.Method.Name == "CheckForSpam" && job.Args[0] == comment.Id),
        It.IsAny<EnqueuedState>());
}

source: https://docs.hangfire.io/en/latest/background-methods/writing-unit-tests.html