简体   繁体   中英

Unit test Hangfire with NSubstitute

I am trying to unit test my class which includes a background job. So far my method which I am testing Enqueues a job and looks like this:

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

My first unit test check if BackgroundJobClient is called and looks like this:

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

All works fine but now I want to check all the parameters if the are correctly sent. I was looking over the HangFire documentation but I couldn't figure that out how can be teste with NSubstitute.

Thank you!

Based on the example in the docs you should be able to test it using something like this:

/* 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>()
);

This is only based on the documented example. The exact arg matching code you need will depend on the specific types you are using.

Use this code:

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

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