Using Moq to Validate Separate Invocations with Distinct Arguments

Posted by Thermite on Stack Overflow See other posts from Stack Overflow or by Thermite
Published on 2011-01-10T00:48:14Z Indexed on 2011/01/10 0:54 UTC
Read the original article Hit count: 127

Filed under:
|
|

I'm trying to validate the values of arguments passed to subsequent mocked method invocations (of the same method), but cannot figure out a valid approach. A generic example follows:

public class Foo
{
    [Dependency]
    public Bar SomeBar
    {
        get;
        set;
    }

    public void SomeMethod()
    {
        this.SomeBar.SomeOtherMethod("baz");
        this.SomeBar.SomeOtherMethod("bag");
    }
}

public class Bar
{
    public void SomeOtherMethod(string input)
    {
    } 
}

public class MoqTest
{
    [TestMethod]
    public void RunTest()
    {
        Mock<Bar> mock = new Mock<Bar>();
        Foo f = new Foo();
        mock.Setup(m => m.SomeOtherMethod(It.Is<string>("baz")));
        mock.Setup(m => m.SomeOtherMethod(It.Is<string>("bag"))); // this of course overrides the first call
        f.SomeMethod();
        mock.VerifyAll();
    }
}

Using a Function in the Setup might be an option, but then it seems I'd be reduced to some sort of global variable to know which argument/iteration I'm verifying. Maybe I'm overlooking the obvious within the Moq framework?

© Stack Overflow or respective owner

Related posts about c#

Related posts about unit-testing