【问题标题】:Fake internal calls of a SUT with FakeItEasy使用 FakeItEasy 对 SUT 进行虚假内部调用
【发布时间】:2020-06-22 15:26:29
【问题描述】:

我有一个处理打印的小型 C# 类。 我想为这个类创建(n)单元测试,使用 假易。我怎么能伪造这个的内部调用 在不伪造整个 SUT 的情况下上课?

例如:

public class MyPrintHandler: IMyPrintHandler
{

    public MyPrintHandler(ILogger<MyPrintHandler> logger) 
    {
    }
         
    // function I want to (unit test
    public  async Task<bool> PrintAsync(string ipaddress)
    {
        try
        {               
            if (!string.IsNullOrWhiteSpace(ipaddress) )
            {
                return await StartPrint(ipaddress); // This cannot be called in a unit test, because it really start printing on a printer.
            }               
        }
        catch (Exception e)
        {                                           
        }
        return false;

    }

    private  async Task<bool> StartPrint(string ipaddress)
    {
      // prints on the printer  
    }



[TestFixture]
public class MyPrintHandlerTests
{
    [Test]
    public void Succes_PrintAsync()
    {            
        using (var fake = new AutoFake())
        {
            // Arrange - configure the fake                   
            var sut = fake.Resolve<MyPrintHandler>();

            // Act
            await sut.PrintAsync("0.0.0.0"); // I want to prevent StartPrint() from being called..                                                 
        }       
    }
}

我怎样才能做到这一点,或者这根本不可能? 提前致谢!

【问题讨论】:

    标签: unit-testing nunit fakeiteasy


    【解决方案1】:

    我通常会说伪造 SUT 是一种反模式,应尽可能避免,因为它会引起混淆。如果您可以重构以引入处理 StartPrinting 方法的协作者,我会强烈考虑这样做。如果这不可能,你可以试试这个,但是

    1. 任何要伪造的方法都必须是virtualabstract,否则FakeItEasy无法拦截
    2. 任何你想伪造的方法都必须是public(或者internal,如果你可以grant dynamic proxy access生产代码的内部)
    3. 然后你会伪造 SUT,指定它应该 call the original (base) methods,最后
    4. 明确覆盖您要拦截的方法的行为

    【讨论】:

    • 感谢您的回答和替代步骤。我选择重构并使用适配器。但是很高兴知道在必要时我可以采取哪些步骤
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多