Al2110
Al2110

Reputation: 576

Unit testing: verifying a method was called, with an object created inside the tested method as parameter

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:

  1. The object being passed into the method is of the correct type.
  2. The object being passed into the method has correct property values.
  3. The other method is being called the correct number of times.

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

Answers (1)

Arsalan Valoojerdi
Arsalan Valoojerdi

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

Related Questions