Writing unit tests¶

I will not tell you anything related to unit testing background methods, because Hangfire does not add any specific changes to them (except IJobCancellationToken interface parameter). Use your favourite tools and write unit tests for them as usual. This section describes how to test that background jobs were created.

All the code examples use the static BackgroundJob class to tell you how to do this or that stuff, because it is simple for demonstrational purposes. But when you want to test a method that invokes static methods, it becomes a pain.

But don’t worry – the BackgroundJob class is just a facade for the IBackgroundJobClient interface and its default implementation – BackgroundJobClient class. If you want to write unit tests, use them. For example, consider the following controller that is used to enqueue background jobs:

  1. public class HomeController : Controller
  2. {
  3. private readonly IBackgroundJobClient _jobClient;
  4.  
  5. // For ASP.NET MVC
  6. public HomeController()
  7. : this(new BackgroundJobClient())
  8. {
  9. }
  10.  
  11. // For unit tests
  12. public HomeController(IBackgroundJobClient jobClient)
  13. {
  14. _jobClient = jobClient;
  15. }
  16.  
  17. public ActionResult Create(Comment comment)
  18. {
  19. ...
  20. _jobClient.Enqueue(() => CheckForSpam(comment.Id));
  21. ...
  22. }
  23. }

Simple, yeah. Now you can use any mocking framework, for example, Moq to provide mocks and check the invocations. The IBackgroundJobClient interface provides only one method for creating a background job – the Create method, that takes a Job class instance, that represents the information about the invocation, and a IState interface implementation to know the creating job’s state.

  1. [TestMethod]
  2. public void CheckForSpamJob_ShouldBeEnqueued()
  3. {
  4. // Arrange
  5. var client = new Mock<IBackgroundJobClient>();
  6. var controller = new HomeController(client.Object);
  7. var comment = CreateComment();
  8.  
  9. // Act
  10. controller.Create(comment);
  11.  
  12. // Assert
  13. client.Verify(x => x.Create(
  14. It.Is<Job>(job => job.Method.Name == "CheckForSpam" && job.Args[0] == comment.Id),
  15. It.IsAny<EnqueuedState>());
  16. }

Note

job.Method property points only to background job’s method information. If you also want to check a type name, use the job.Type property.

原文:

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