使用最小起订量测试对不同 class 的调用
Using Moq to test call to different class
问题
我有以下方法:
public void ParseRebootData(RebootDeviceDto rebootDeviceDto)
{
if (rebootDeviceDto.RebootAtUtc.CompareTo(DateTime.UtcNow) <= 0) // if time is either now or in the past, reboot instantly
{
Console.WriteLine("Rebooting machine now");
await new Tasks.Reboot().RebootNow(); // <-- I want to test this line
}
else // schedule the reboot
{
Console.WriteLine($"Scheduling reboot at {rebootDeviceDto.RebootAtUtc}");
_backgroundJobClient.Schedule<Tasks.Reboot>(x => x.RebootNow(), rebootDeviceDto.RebootAtUtc);
}
}
_backgroundJobClient
在构造函数中通过依赖注入传递。
我想测试行 await new Tasks.Reboot().RebootNow();
是否被调用,使用 Moq 的 Verify
方法。
我的问题
由于Tasks.Reboot
只是一个class,没有通过依赖注入,不知道能不能测试这个调用
其中一个解决方案可能是创建一个 TasksService
,我可以在我的单元测试中覆盖它(这可能不是一个坏主意)但我想知道这是否可能,因为.
使用 Moq,您只能从外部提供模拟对象。您不能用另一个实例替换静态实例。
还有其他测试框架可以做到这一点,例如Microsoft Fakes 的填充程序。另一方面,垫片应该与第三方代码一起使用。如果您可以更改代码并注入 TasksService,那么这是解耦代码的首选方法。
问题
我有以下方法:
public void ParseRebootData(RebootDeviceDto rebootDeviceDto)
{
if (rebootDeviceDto.RebootAtUtc.CompareTo(DateTime.UtcNow) <= 0) // if time is either now or in the past, reboot instantly
{
Console.WriteLine("Rebooting machine now");
await new Tasks.Reboot().RebootNow(); // <-- I want to test this line
}
else // schedule the reboot
{
Console.WriteLine($"Scheduling reboot at {rebootDeviceDto.RebootAtUtc}");
_backgroundJobClient.Schedule<Tasks.Reboot>(x => x.RebootNow(), rebootDeviceDto.RebootAtUtc);
}
}
_backgroundJobClient
在构造函数中通过依赖注入传递。
我想测试行 await new Tasks.Reboot().RebootNow();
是否被调用,使用 Moq 的 Verify
方法。
我的问题
由于Tasks.Reboot
只是一个class,没有通过依赖注入,不知道能不能测试这个调用
其中一个解决方案可能是创建一个 TasksService
,我可以在我的单元测试中覆盖它(这可能不是一个坏主意)但我想知道这是否可能,因为.
使用 Moq,您只能从外部提供模拟对象。您不能用另一个实例替换静态实例。
还有其他测试框架可以做到这一点,例如Microsoft Fakes 的填充程序。另一方面,垫片应该与第三方代码一起使用。如果您可以更改代码并注入 TasksService,那么这是解耦代码的首选方法。