我有以下方法:
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();
如果它被称为,用起订量的Verify
方法。
由于Tasks.Reboot
仅仅是一个类,它不是通过依赖注入过去了,我不知道我是否可以测试这个电话。
解决的办法之一可能是创建一个TasksService
,我可以在我的单元测试覆盖(这可能不是一个坏主意),但我想知道这是不可能的,因为是。
随着起订量,你只能提供来自外部的模拟对象。你不能替换另外一个静态实例。
还有其他的测试框架,可以做到这一点,例如微软Fakes的垫片。在另一方面,垫片应该与第三方代码中使用。如果你可以改变代码,并注入TasksService,这是为了分离代码的首选方法。