Search code examples
c#mockingmoqxunit

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


Assume that I have the following function "foo" which I want to unit test:

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" is going to read some data expecting specific byte streams that are going to be evaluated in foo after each "ReadBytes"-call.

Now, when calling "foo" in the unit test, how can I influence the return value of "ReadBytes" each time in a specific way? How do I set up the mock?

So for testing I would need to do something like...

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...
    }
}

Solution

  • Looks like SetupSequence is what you are looking for

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

    Reference Moq Quickstart: sequential calls