Hangfire 与 NSubstitute 的经常性工作

问题描述 投票:0回答:1

我需要使用 NSubstitute 对我的hangifre 经常性工作进行单元测试,我的服务类如下,现在我需要对其运行测试。

public class ItemService : IItemService, IJobConfigurationService
 {
     private readonly IItemRepository itemRepository;
     private readonly ISettingRepository settingRepository;
     private readonly ILogger<ItemService> logger;

     public ItemService(IItemRepository itemRepository
         ,ISettingRepository settingRepository
         ,ILogger<ItemService> logger)
     {
         this.itemRepository = itemRepository;
         this.settingRepository = settingRepository;
         this.logger = logger;
     }

     public void ConfigureJob(string cronExpression)
     {
         RecurringJob.AddOrUpdate("PermanentlyDeleteItemsAsync", () =>
             PermanentlyDeleteItemsAsync(), cronExpression);
     }

     public async Task PermanentlyDeleteItemsAsync()
     {
         //some logic here
     }
 }

我尝试了这样的单元测试方法,

[Fact]
public async Task ConfigureJob_AddsOrUpdateRecurringJobAsync()
{
    // Arrange
    var itemRepository = Substitute.For<IItemRepository>();
    var settingRepository = Substitute.For<ISettingRepository>();
    var logger = Substitute.For<ILogger<ItemService>>();
    var mockRecurringJobManager = Substitute.For<IRecurringJobManager>();

    var service = new ItemService(itemRepository, settingRepository, logger);
    string cronExpression = "0 * * * *"; // Every hour

    // Act
    service.ConfigureJob(cronExpression);

    // Assert
    mockRecurringJobManager.Received().AddOrUpdate(Arg.Any<string>(),
        () => service.PermanentlyDeleteItemsAsync(), cronExpression);
}

这不起作用,这是正确的测试方法吗?因为我是 Hangfire 的新手

c# .net xunit hangfire nsubstitute
1个回答
0
投票

这不起作用,因为

IRecurringJobManager
没有该合同的方法!这就是扩展方法。

下划线方法如下所示:

void AddOrUpdate(
    [NotNull] string recurringJobId, 
    [NotNull] Job job, 
    [NotNull] string cronExpression, 
    [NotNull] RecurringJobOptions options);

您可以在GitHub上看到它。

所以你的断言看起来像这样:

 // Assert
        mockRecurringJobManager.Received().AddOrUpdate(Arg.Any<string>(), Arg.Any<Job>(), Arg.Any<string>(), Arg.Any<RecurringJobOptions>());

可以选择创建存根或假版本 - 您可以在其中使用自己的

IRecurringJobManager
实现来代替替代品:

public class RecuringJobManagerFake : IRecurringJobManager
 {
     public List<Hangfire.Common.Job> Jobs = new List<Hangfire.Common.Job>(); 
     public void AddOrUpdate([NotNull] string recurringJobId, [NotNull] Hangfire.Common.Job job, [NotNull] string cronExpression, [NotNull] RecurringJobOptions options)
     {
         Jobs.Add(job);
     }

     public void RemoveIfExists([NotNull] string recurringJobId)
     {
         throw new System.NotImplementedException();
     }

     public void Trigger([NotNull] string recurringJobId)
     {
         throw new System.NotImplementedException();
     }
 }

您可以保存并检查

IRecurringJobManager
收到的所有内容。

© www.soinside.com 2019 - 2024. All rights reserved.