Reputation: 576
Description of the problem
A method to be tested creates objects of some type, let's call it Item
. It initialises these objects' properties with data passed into it.
This method calls another method, which takes an Item
as a parameter. How can it be made sure that this call is made correctly? That is, the following would need to be verified:
Assume we are using NUnit and FakeItEasy.
Code
public class Controller
{
IService service {get; set;}
// dependency injection, can use fakes
public Controller(IService service) {
this.service = service;
}
public void methodToTest(string itemName, string itemDescription, int quantity)
{
Item newItem = new Item
{
name = name,
description = description
}
for (int i = 1; i <= quantity; i++)
{
// need to verify that doSomething() is called with a parameter of type Item
// and that it is called quantity times
// and that newItem has correct parameters
service.doSomething(newItem);
}
}
}
Upvotes: 1
Views: 2888
Reputation: 1026
You can try this:
[Test]
public void MethodToTest_Should_Call_Service_Correctly()
{
var service = A.Fake<IService>();
var controller = new Controller(service);
controller.methodToTest("some-item", "some-description", 5);
var expectedItem = new Item
{
Name = "some-item",
Description = "some-description"
};
A.CallTo(() => service.DoSomething(expectedItem)).MustHaveHappened(5, Times.Exactly);
}
Be careful that too much mocking lead to rigid tests because they are coupled to implementation details.
Upvotes: 3