简体   繁体   中英

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

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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM