使用起订量来测试调用不同类

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

The problem

我有以下方法:

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方法。

My question

由于Tasks.Reboot仅仅是一个类,它不是通过依赖注入过去了,我不知道我是否可以测试这个电话。

解决的办法之一可能是创建一个TasksService,我可以在我的单元测试覆盖(这可能不是一个坏主意),但我想知道这是不可能的,因为是。

c# unit-testing moq
1个回答
4
投票

随着起订量,你只能提供来自外部的模拟对象。你不能替换另外一个静态实例。

还有其他的测试框架,可以做到这一点,例如微软Fakes的垫片。在另一方面,垫片应该与第三方代码中使用。如果你可以改变代码,并注入TasksService,这是为了分离代码的首选方法。

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