Reputation: 3366
I am getting
Parameter count mismatch.
exception when I am trying to run the below unit test. I am passing the relevant params and count is correct. Why it is throwing an exception?
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);
}
Signature in the interface
string Receive(List<TransactionVM> transactionVMList, string priceChangeStatus);
I am getting the exception when I am executing this.MockOrderManager.Receive(transactionList, "Permanent");
line in CanReceiveOrder()
Upvotes: 1
Views: 2559
Reputation: 7463
It looks like your .Returns()
method does not implement the correct signature when you are doing the setup (hence the 'mismatch' error).
The .Returns()
method has to take a lambda function which matches the Receive()
method signature. Then you have access to the parameters with which the mock object was called, which would usually determine the returned value.
Try this instead:
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";
});
The bigger problem is that it looks like you are testing your mock, rather than your business object. Your test class is called OrderServiceTest
, but you never create an order service.
My advice for creating unit tests is to use the 'should' naming convention and a 'AAA' (Arrange, Act, Assert) layout. Here's an example loosely based on your question:
[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"));
}
I think this makes it very clear what you are testing, and what you expect your test to do.
Upvotes: 2