在我的网上商店应用程序中,我有一个“购物车”类,可以添加、删除和计算商品的总价值。数据模型如下:1 个项目包含 1 个产品和 1 个运输。产品有价格字段,运输有成本字段。这是购物车类代码:
public class CartLine
{
public Item Item { get; set; }
public int Quantity { get; set; }
}
public class Cart
{
private List<CartLine> lineCollection = new List<CartLine>();
// methods:
// Add(Item item, int quantity)
// Remove(Item item)
public decimal ComputeTotalProductValue()
{
return lineCollection.Sum(l => l.Item.Product.Price*l.Quantity);
}
// methods with the same principle:
// ComputeTotalShippingValue()
// ComputeOveralValue()
}
这是我的单元测试(当然不起作用):
[TestMethod]
public void Can_Compute_Total_Values()
{
// Arrange
var itemMock = new Mock<IItemsRepository>();
itemMock.Setup(i => i.GetItems()).Returns(new[]
{
new Item { ItemId = 1, ProductId = 1, ShippingId = 1 },
new Item { ItemId = 2, ProductId = 2, ShippingId = 2 }
});
var productMock = new Mock<IProductRepository>();
productMock.Setup(p => p.GetProducts()).Returns(new[]
{
new Product { ProductId = 1, Price = 10 },
new Product { ProductId = 2, Price = 20 }
});
var shippingMock = new Mock<IShippingRepository>();
shippingMock.Setup(s => s.GetShippings()).Returns(new[]
{
new Shipping { ShippingId = 1, Cost = 2 },
new Shipping { ShippingId = 2, Cost = 5 }
});
var item1 = itemMock.Object.GetItems().ToArray()[0];
var item2 = itemMock.Object.GetItems().ToArray()[1];
var target = new Cart();
//Act
target.Add(item1, 2);
target.Add(item2, 4);
decimal totalProduct = target.ComputeTotalProductValue();
decimal totalShipping = target.ComputeTotalShippingValue();
decimal overalSum = target.ComputeOveralValue();
// Assert
Assert.AreEqual(totalProduct, 100);
Assert.AreEqual(totalShipping, 24);
Assert.AreEqual(overalSum, 124);
}
}
该问题可能与将项目绑定到产品和运输有关。我怎样才能做到这一点?
提前致谢!