单元测试中的参数计数不匹配

时间:2018-01-16 06:46:35

标签: c# unit-testing parameter-passing

我正在

  

参数计数不匹配。

当我尝试运行以下单元测试时,

异常。我正在通过相关的参数并且计数是正确的。为什么会抛出异常?

List<TransactionVM> transactionList = new List<TransactionVM> {
    new TransactionVM {OrderDetailID = 1, QuantityReceived=125, UnitCost=100.00},
    new TransactionVM {OrderDetailID = 1, QuantityReceived=130, UnitCost=200.00},
};

public OrderServiceTest()
{
    Mock<IOrderManager> mockOrderManager = new Mock<IOrderManager>();
    mockOrderManager.Setup(mr => mr.Receive(It.IsAny<List<TransactionVM>>(), It.IsAny<string()))
                    .Returns((TransactionVM target) =>
                             {
                                 target.RoleID = transactionList.Count() + 1;
                                 transactionList.Add(target);
                                 return "OrderReceived";
                             });
    this.MockOrderManager = mockOrderManager.Object;
}

[TestMethod]
public void CanReceiveOrder()
{
    List<TransactionVM> transactionList = new List<TransactionVM> {
        new TransactionVM {OrderDetailID = 1, QuantityReceived=125, UnitCost=100.00}
    };

    this.MockOrderManager.Receive(transactionList, "Permanent");
    int productCount = transactionList.Count();
    Assert.AreEqual(3, transactionList);
}

界面中的签名

string Receive(List<TransactionVM> transactionVMList, string priceChangeStatus);

我在this.MockOrderManager.Receive(transactionList, "Permanent");

中执行CanReceiveOrder()行时遇到异常

1 个答案:

答案 0 :(得分:2)

在进行设置时,您的.Returns()方法似乎没有实现正确的签名(因此“不匹配”错误)。

.Returns()方法必须采用与Receive()方法签名匹配的lambda函数。然后,您可以访问调用模拟对象的参数,这通常会确定返回的值。

请改为尝试:

mockOrderManager.Setup(mr => mr.Receive(It.IsAny<List<TransactionVM>>(), It.IsAny<string()))
                .Returns((List<TransactionVM> target, string status) =>
                         {
                             // update logic here...
                             // target.RoleID = transactionList.Count() + 1;
                             // transactionList.Add(target);
                             return "OrderReceived";
                         });

更大的问题是,您似乎正在测试您的模拟,而不是您的业务对象。您的测试类名为OrderServiceTest,但您从未创建订单服务。

我对创建单元测试的建议是使用'should'命名约定和'AAA'(Arrange,Act,Assert)布局。以下是一个基于您的问题的示例:

[TestMethod]
public void OrderService_ShouldReceiveOrder()
{
    // Arrange
    var mockOrderManager = new Mock<IOrderManager>();
    mockOrderManager.Setup(It.IsAny<List<TransactionVM>>(), "Permanent")
                    .Returns("OrderReceived");

    var orderService = new OrderService(mockOrderManager.Object);
    orderService.AddOrder(new TransactionVM());

    // Act
    orderService.ProcessOrders();

    // Assert
    mockOrderManager.Verify(_ => _.Receive(It.IsAny<List<TransactionVM>>(),
                                           "Permanent"));
}

我认为这清楚地说明了您正在测试的内容以及您希望测试的内容。