【问题标题】:Verify using Moq that only these two method calls where called, and nothing else使用 Moq 验证只有这两个方法调用被调用,没有别的
【发布时间】:2013-02-14 18:23:12
【问题描述】:

我正在使用最小起订量进行验证和单元测试。我想验证是否使用参数 1 和参数 5 调用了方法“Add”,并且 not called 用于除这些之外的任何其他值。

是否可以创建验证,类似于下面的代码? (注意这不是实际代码!)

mock.Verify(x=>x.Add(1), Times.Once());
mock.Verify(x=>x.Add(5), Times.Once());
mock.Verify(x=>x.Add(It.IsAny<int>()), Times.Never());

【问题讨论】:

    标签: unit-testing mocking tdd moq


    【解决方案1】:

    您可以试试这个,将 lambda 表达式传递给第三次验证以排除任何不同于 1 和 5 的值。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Moq;
    
    namespace Tests.x21
    {
        public interface IMyInterface
        {
            void Add(int num);
        }
    
        public class Executor
        {
            private IMyInterface _dep;
    
            public Executor(IMyInterface dep)
            {
                _dep = dep;
            }
    
            public void Execute()
            {
                _dep.Add(1);
                _dep.Add(5);
                _dep.Add(4);    // comment to make the test work
            }
        }
    
        [TestClass]
        public class UnitTest21
        {
            [TestMethod]
            public void TestMethod1()
            {
                var mock = new Mock<IMyInterface>();
                var executor = new Executor(mock.Object);
                executor.Execute();
                mock.Verify(x => x.Add(1), Times.Once());
                mock.Verify(x => x.Add(5), Times.Once());
                mock.Verify(m => m.Add(It.Is<int>(num => num != 1 && num != 5)), Times.Never());
            }
        }
    }
    

    【讨论】:

    • 是的,可以。我所做的一个解决方法是,如果我只想要这两个实例,那么显然不应该有任何其他调用。在断言之后,我做了mock.Verify(x =&gt; x.Add(It.IsAny&lt;int&gt;(), Times.Exactly(2)))。这样,如果它被调用为任何其他值,它不会只有两个。在我看来,避免编写所有重复的组合。
    • 是的,这是一个好方法!无论如何,我想指出如何使用 lambda 表达式来验证传递给模拟对象的值。
    猜你喜欢
    • 2011-03-11
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    相关资源
    最近更新 更多