简体   繁体   English

如何使用xunit单元测试包含hangfire的功能

[英]How to use xunit to unit test contains the function of hangfire

The develop language is dotnet core 3.0.开发语言是 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我在测试类中配置了 hanfire,就像这样

[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.在 Hangfire 的文档页面上,您有一个关于如何为依赖于 Hangfire 的方法编写单元测试的示例。 It's important to highlight that you still need to mock it.重要的是要强调您仍然需要模拟它。 Using Moq, it would be something like: new Mock<IBackgroundJobClient>();使用 Moq,它会是这样的: 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来源: https : //docs.hangfire.io/en/latest/background-methods/writing-unit-tests.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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