开发者

Using Moq to Validate Separate Invocations with Distinct Arguments [duplicate]

This question already has answers here: How to test method call order with Moq (6 answers) Closed 2 years ago.

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?


Not that I was completely wrong or Termite too tolerant, but the better answer is demonstrated by the following code:

public interface IA
    {
        int doA(int i);
    }
    public class B
    {
        private IA callee;
        public B(IA callee)
        {
            this.callee = callee;
        }
        public int doB(int i)
        {
            Console.WriteLine("B called with " + i);
            var res = callee.doA(i);
            Console.WriteLine("Delegate returned " + res);
            return res;
        }
    }
    [Test]
    public void TEST()
    {
        var mock = new Mock<IA>();
        mock.Setup(a => a.doA(It.IsInRange(-5, 100, Range.Exclusive))).Returns((int i) => i * i);
        var b = new B(mock.Object);
        for (int i = 0; i < 10; i++)
        {
            b.doB(i);
        }

        mock.Verify(a => a.doA(It.IsInRange(0, 4, Range.Inclusive)), Times.Exactly(5));
        mock.Verify(a => a.doA(It.IsInRange(5, 9, Range.Inclusive)), Times.Exactly(5));
        mock.Verify(a => a.doA(It.Is<int>(i => i < 0)), Times.Never());
        mock.Verify(a => a.doA(It.Is<int>(i => i > 9)), Times.Never());
        mock.Verify(a => a.doA(It.IsInRange(3, 7, Range.Inclusive)), Times.Exactly(5));

        // line below will fail
        // mock.Verify(a => a.doA(It.IsInRange(3, 7, Range.Inclusive)), Times.Exactly(7));
    }

This shows that the setup is completely separated from validation. In some cases it means that argument matching has to be done twice :(

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜