1

如何告诉 Moq 期待多个电话,以便我仍然可以使用MockRepositoryto VerifyAll,如下所示?

[TestFixture]
public class TestClass
{
    [SetUp]
    public void SetUp()
    {
        _mockRepository = new MockRepository(MockBehavior.Strict);
        _mockThing = _mockRepository.Create<IThing>();

        _sut = new Sut(_mockThing.Object);
    }

    [TearDown]
    public void TearDown()
    {
        _mockRepository.VerifyAll();
    }

    private Mock<IThing> _mockThing;

    private MockRepository _mockRepository;

    [Test]
    public void TestManyCalls(Cell cell)
    {
       _mockThing.SetUp(x => x.DoSomething()).Return(new DoneStatus());
    }
}

我知道您可以在验证时执行此操作,但随后我必须独立验证所有内容。有没有告诉它会发生什么,而不是在事件发生后验证它?

类似于:

_mockThing.SetUp(x => x.DoSomething()).Return(new DoneStatus()).Times(20);

基本上,我想在测试开始时设定我所有的期望,而不是将它们放在多个地方。

4

1 回答 1

1

暂时将 MockRepository 放在一边,我创建了一个继承自的类,Mock以提供您所追求的功能。一、用法(XUnit语法):

    [Fact]
    public void SomeTest()
    {
        var mock = new Mock2<IDependency>();
        var sut = new Sut(mock.Object);
        mock.SetupAndExpect(d => d.DoSomething(It.IsAny<string>(), It.IsAny<long>()),Times.Once).Returns(3);
        mock.SetupAndExpect(d => d.DoSomethingNoReturn(It.IsAny<string>()), Times.Once);
        mock.SetupAndExpect(d => d.DoSomethingNoReturn(It.IsAny<string>()), Times.Once);
        sut.CallDoSomething();
        mock.VerifyAllExpectations();
    }

SetupAndExpect方法是Setup允许Times通过的替代方法。VerifyAllExpectations相当于VerifyAll。_ 如果你愿意,你可以摆弄这些名字。

该类Mock2存储expression并在 期间times传递以SetupAndExpect供以后使用VerifyAllExpectations

在我展示Mock2代码并讨论MockRepository解决方案之前,先解释一下冗长的内容。让它适用于没有返回值的模拟方法是相当容易的,因为表达式都有一个比模拟类型更通用的类型。但是,对于具有返回值的方法,要调用的基础验证是Mock.Verify<TResult>(...). 为了能够在VerifyAllExpectations我最终使用反射期间绑定到正确关闭的方法。我确信修改 Mock 本身以放入此功能将允许一个不那么 hacky 的解决方案。

现在,回到存储库:我的想法是修改Mock2,而不是继承自Mock,它接受一个实例Mock作为构造函数参数并使用它来调用Setupand VerifyMockRepository然后,您可以在( ??)上编写一个新的扩展方法,该方法Create2调用原始实例MockRepository.Create并将创建的Mock实例传递给实例的构造函数,Mock2然后将其返回。

SetupAndExpect最后一个替代VerifyAllExpectations方法是在Mock. 但是,期望信息的存储可能必须处于某种静态状态并面临清理问题。

这是Mock2代码:

public class Mock2<T> : Mock<T> where T:class
{
    private readonly Dictionary<Type, List<Tuple<Expression,Func<Times>>>> _resultTypeKeyedVerifications =
        new Dictionary<Type, List<Tuple<Expression, Func<Times>>>>();

    private readonly List<Tuple<Expression<Action<T>>, Func<Times>>> _noReturnTypeVerifications = 
        new List<Tuple<Expression<Action<T>>, Func<Times>>>();

    public ISetup<T, TResult> SetupAndExpect<TResult>(Expression<Func<T, TResult>> expression, Func<Times> times)
    {
        // Store the expression for verifying in VerifyAllExpectations
        var verificationsForType = GetVerificationsForType(typeof(TResult));
        verificationsForType.Add(new Tuple<Expression, Func<Times>>(expression, times));

        // Continue with normal setup
        return Setup(expression);
    }

    public ISetup<T> SetupAndExpect(Expression<Action<T>> expression, Func<Times> times)
    {
        _noReturnTypeVerifications.Add(new Tuple<Expression<Action<T>>, Func<Times>>(expression, times));
        return Setup(expression);
    }

    private List<Tuple<Expression, Func<Times>>> GetVerificationsForType(Type type)
    {
        // Simply gets a list of verification info for a particular return type,
        // creating it and putting it in the dictionary if it doesn't exist.
        if (!_resultTypeKeyedVerifications.ContainsKey(type))
        {
            var verificationsForType = new List<Tuple<Expression, Func<Times>>>();
            _resultTypeKeyedVerifications.Add(type, verificationsForType);
        }
        return _resultTypeKeyedVerifications[type];
    }

    /// <summary>
    /// Use this instead of VerifyAll for setups perfomed using SetupAndRespect
    /// </summary>
    public void VerifyAllExpectations()
    {
        VerifyAllWithoutReturnType();
        VerifyAllWithReturnType();
    }

    private void VerifyAllWithoutReturnType()
    {
        foreach (var noReturnTypeVerification in _noReturnTypeVerifications)
        {
            var expression = noReturnTypeVerification.Item1;
            var times = noReturnTypeVerification.Item2;
            Verify(expression, times);
        }
    }

    private void VerifyAllWithReturnType()
    {
        foreach (var typeAndVerifications in _resultTypeKeyedVerifications)
        {
            var returnType = typeAndVerifications.Key;
            var verifications = typeAndVerifications.Value;

            foreach (var verification in verifications)
            {
                var expression = verification.Item1;
                var times = verification.Item2;

                // Use reflection to find the Verify method that takes an Expression of Func of T, TResult
                var verifyFuncMethod = GetType()
                    .GetMethods(BindingFlags.Instance | BindingFlags.Public)
                    .Single(IsVerifyMethodForReturnTypeAndFuncOfTimes)
                    .MakeGenericMethod(returnType);

                // Equivalent to Verify(expression, times)
                verifyFuncMethod.Invoke(this, new object[] {expression, times});
            }
        }
    }

    private static bool IsVerifyMethodForReturnTypeAndFuncOfTimes(MethodInfo m)
    {
        if (m.Name != "Verify") return false;
        // Look for the single overload with two funcs, which is the one we want
        // as we're looking at verifications for functions, not actions, and the
        // overload we're looking for takes a Func<Times> as the second parameter
        var parameters = m.GetParameters();
        return parameters.Length == 2
               && parameters[0] // expression
                   .ParameterType // Expression
                   .GenericTypeArguments[0] // Func
                   .Name == "Func`2"
               && parameters[1] // times
                   .ParameterType // Func
                   .Name == "Func`1";
    }
}

最后警告:这只是轻微测试,不会同时测试。它没有等效于Verifythat takeTimes而不是Func<Times>. 可能有一些更好的方法名称和/或原因,为什么这通常都是一个坏主意。

我希望它对您或某人有用!

于 2013-09-29T22:28:41.767 回答