我在单元测试中使用 MOQ 时遇到了一些奇怪的行为:
给定以下测试:
[Fact]
public void ShoppingCart_ShouldIncrementQuantity_WhenAddingDuplicateItem()
{
var cart = new ShoppingCart();
var item1 = GetMockItem("Test");
var item2 = GetMockItem("Test", quantity: 2);
cart.AddItem(item1.Object);
cart.AddItem(item2.Object);
cart.Items.Single(x => x.Sku == "Test").Quantity
.Should().Be(3);
}
private Mock<IShoppingCartItem> GetMockItem(string sku, decimal price = 10, int quantity = 1)
{
var mock = new Mock<IShoppingCartItem>();
mock.Setup(x => x.Sku).Returns(sku);
mock.Setup(x => x.Price).Returns(price);
mock.Setup(x => x.Quantity).Returns(quantity);
return mock;
}
这是正在测试的代码:
public void AddItem(IShoppingCartItem item)
{
Enforce.ArgumentNotNull(item, "item");
var existingItem = this.Items.SingleOrDefault(x => x.Sku == item.Sku);
if (existingItem != null)
{
existingItem.Quantity += item.Quantity;
}
else
{
this.Items.Add(item);
}
}
我得到这个结果:Test 'Titan.Tests.ShoppingCartTests.ShoppingCart_ShouldIncrementQuantity_WhenAddingDuplicateItem' failed: Expected 3, but found 1.
我很困惑,或者我只是有一个愚蠢的时刻!