使用Moq验证具有不同参数的单独调用

时间:2011-01-10 00:48:14

标签: c# unit-testing moq

我正在尝试验证传递给后续模拟方法调用(相同方法)的参数值,但无法找出有效的方法。一个通用的例子如下:

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

在安装程序中使用函数可能是一个选项,但似乎我将被简化为某种全局变量,以了解我正在验证哪个参数/迭代。也许我忽视了Moq框架内的明显内容?

2 个答案:

答案 0 :(得分:1)

Moq区分设置和验证。您可以尝试使用

之类的东西来代替VerifyAll()

mock.Verify(m => m.SomeOtherMethod(It.Is("baz")), Times.Exactly(1)); mock.Verify(m => m.SomeOtherMethod(It.Is("bag")), Times.Exactly(1));

我要赶回家......也许别人有更好的答案:) ... oops发现了一个副本: How to test method call order with Moq

答案 1 :(得分:1)

不是说我完全错了或白蚁太宽容了, 但是下面的代码证明了更好的答案:

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

这表明设置与验证完全分开。在某些情况下,这意味着参数匹配必须进行两次:(