【问题标题】:Using Moq to Validate Separate Invocations with Distinct Arguments [duplicate]使用 Moq 验证具有不同参数的单独调用 [重复]
【发布时间】:2011-01-10 00:48:14
【问题描述】:

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

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 框架中的明显内容?

【问题讨论】:

    标签: c# unit-testing moq


    【解决方案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));
        }
    

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

    【讨论】:

      猜你喜欢
      • 2011-07-11
      • 2019-02-26
      • 1970-01-01
      • 2011-06-24
      • 2012-11-09
      • 1970-01-01
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      相关资源
      最近更新 更多