It.IsAny <cart>(),It.IsAny <shippingdetails>(),Times.Never()。他们做了什么?</shippingdetails> </cart>

时间:2011-09-21 17:15:22

标签: c# unit-testing mocking moq

我想知道你是否可以帮我理解以下内容:

        mock.Verify(m => m.ProcessOrder(It.IsAny<Cart>(), 
                                        It.IsAny<ShippingDetails>()),
                         Times.Never());

测试方法:

[TestMethod]
public void Cannot_Checkout_Empty_Cart()
{
    // Arrange - create a mock order processor
    Mock<IOrderProcessor> mock = new Mock<IOrderProcessor>();

    // Arrange - create an empty cart
    Cart cart = new Cart();

    // Arrange - create shipping details
    ShippingDetails shippingDetails = new ShippingDetails();

    // Arrange - create an instance of the controller
    CartController target = new CartController(null, mock.Object);

    // Act
    ViewResult result = target.Checkout(cart, shippingDetails);

    // Assert - check that the order hasn't been passed on to the processor
    mock.Verify(m => m.ProcessOrder(It.IsAny<Cart>(), It.IsAny<ShippingDetails>()), Times.Never());

    // Assert - check that the method is returning the default view
    Assert.AreEqual("", result.ViewName);

    // Assert - check that we are passing an invalid model to the view
    Assert.AreEqual(false, result.ViewData.ModelState.IsValid);
}

3 个答案:

答案 0 :(得分:5)

It.IsAny<Cart>匹配Cart类型的任何值。由于您有Times.Never,因此您实际使用这两个参数(Card,ShippingDetails)验证该方法是否从未被调用

答案 1 :(得分:2)

@Wiktor说得对,但只是为了澄清差异。

当前检查确保未使用 ANY 购物车或 ANY 送货详细信息调用该方法。这可能看起来过分,因为这可能就足够了:

// Assert - check that the order hasn't been passed on to the processor
mock.Verify(m => m.ProcessOrder(cart, shippingsDetails), Times.Never());

毕竟很可能使用给定的购物车和运输细节完成处理。但是,可能已经克隆了购物车,或者某些运输详细信息可能已从用户首选项或其他内容加载,It.IsAny<T>允许您检查方法是否未被调用,无论参数如何,否则验证只会在那些特定实例作为参数发生。

修改

回答评论。想象一下,另一个测试,你要检查订单是否已经处理,并且使用正确的参数进行处理,而不是使用一些不同的用户购物车和运输细节:

// Arrange - create an empty cart
Cart cart = new Cart();

// Arrange - create shipping details
ShippingDetails shippingDetails = new ShippingDetails();

// Arrange - create an instance of the controller
CartController target = new CartController(null, mock.Object);

// Act
ViewResult result = target.Checkout(cart, shippingDetails);

//Assert - check the order was processed once with the 
//correct cart and shipping details
mock.Verify(m => m.ProcessOrder(cart, shippingDetails), Times.Once());

现在,如果未使用与预期完全相同的购物车和送货详细信息调用ProcessOrder方法,则此测试将失败。如果碰巧使用其他用户购物车或运送详细信息,则测试将失败。

希望这清楚地明确指定参数和使用It.IsAny<T>

之间的区别

答案 2 :(得分:1)

它正在验证在测试过程中使用任何类型的ProcessOrderCart作为参数调用方法ShippingDetails 从不