繁体   English   中英

Function 被测 “foo” 调用外部 function “bar(baz)” 多次 => 如何针对每个调用专门修改 “baz” 的返回值?

[英]Function under test “foo” calls external function “bar(baz)” multiple times => How can return value of “baz” be modified specifically for each call?

假设我有以下 function "foo" 我想对其进行单元测试:

class FooClass
{
    IBar _bar; 
    
    Foo(IBar bar)
    {
        _bar = bar;
    }
    
    void foo()
    {
        byte[] someBytes;
        someBytes = _bar.ReadBytes();
        
        if (someBytes != Expectation1)
        {
            throw new Exception("Byte stream doesn't match expectations");
        }

        someBytes = _bar.ReadBytes();
        
        if (someBytes != Expectation2)
        {
            throw new Exception("Byte stream doesn't match expectations");
        }
        ...
    }
}

“_bar.ReadBytes”将读取一些期望特定字节流的数据,这些数据将在每次“ReadBytes”调用后在 foo 中进行评估。

现在,在单元测试中调用“foo”时,如何以特定方式每次影响“ReadBytes”的返回值? 如何设置模拟?

所以为了测试我需要做一些类似的事情......

public class FooClassTests
{
    [Fact]
    public void Test_Foo()
    {
        Mock<IBar> mockBar = new Mock<IBar>();
        mockComInterface.Setup(mock => mock.ReadBytes()).Returns(new byte[] {}); // returns empty byte array
        
        FooClass fooObject = new FooClass();
        fooObject.foo();

        Assert.something...
    }
}

看起来SetupSequence是您正在寻找的

//...

Mock<IBar> mockBar = new Mock<IBar>();
mockBar.SetupSequence(mock => mock.ReadBytes())
    .Returns(expectation1ByteArray)  // will be returned on 1st invocation
    .Returns(expectation2ByteArray); // will be returned on 2nd invocation

FooClass fooObject = new FooClass(mockBar.Object);

//...

参考起订量快速入门:顺序调用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM