被测函数"foo" 多次调用外部函数"bar(baz)" => 每次调用如何具体修改"baz" 的return 值?

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

假设我有以下函数“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”的return值?如何设置模拟?

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

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);

//...

引用Moq Quickstart: sequential calls