【问题标题】:Unit test Hangfire with NSubstitute使用 NSubstitute 进行单元测试 Hangfire
【发布时间】:2021-12-03 19:22:27
【问题描述】:

我正在尝试对包含后台作业的课程进行单元测试。到目前为止,我正在测试的方法将工作排入队列,如下所示:

public void SendSms(SmsContent content){
      .... 
      _backgroundJobClient.Enqueue<ISms>(x => x.Send(content));
      ....
}

我的第一个单元测试检查是否调用了 BackgroundJobClient 并且看起来像这样:

 Assert.Equal(1,_backgroundJobClient.ReceivedCalls().Count());
  

一切正常,但现在我想检查所有参数是否正确发送。我正在查看HangFire documentation,但我无法弄清楚如何使用 NSubstitute 进行测试。

谢谢!

【问题讨论】:

    标签: c# unit-testing hangfire nsubstitute


    【解决方案1】:

    基于example in the docs,您应该能够使用以下方式对其进行测试:

    /* Moq example:
    client.Verify(x => x.Create(
        It.Is<Job>(job => job.Method.Name == "CheckForSpam" && job.Arguments[0] == comment.Id.ToString()),
        It.IsAny<EnqueuedState>());
    */
    
    // Ported to NSubstitute:
    _backgroundJobClient.Received().Create(
        Arg.Is<Job>(job => job.Method.Name == "CheckForSpam" && job.Arguments[0] == comment.Id.ToString()),
        Arg.Any<EnqueuedState>()
    );
    

    这仅基于记录的示例。您需要的确切 arg 匹配代码将取决于您使用的特定类型。

    【讨论】:

      【解决方案2】:

      使用此代码:

      _backgroundJobClient.ReceivedWithAnyArgs()
                         .Enqueue<ISms>(x => x.Send(default));
      

      【讨论】:

      • 这似乎工作正常,但是,我无法弄清楚如何检查发送到 Send 方法的参数。
      • 我不确定。测试这段代码:_backgroundJobClient.Received().Enqueue&lt;ISms&gt;(x =&gt; x.Send(content));
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-17
      相关资源
      最近更新 更多