Unit Testing: Verify a Method Call Ignoring the Parameters


I use Moq extensively when unit testing my applications. One of the nice features of Moq (and any other Mocking framework) is that you can verify which methods were called on a given interface during a test. By default, if you have a method on an interface that accepts parameters and you want to verify that it is called, you have to specify the exact parameters that should have been used in the method call for it to pass the test. Example:

public interface ICompanyService
{
    void Add(Company company);
}

[Test]
public void SignUp_Action_Calls_CompanyService_Add_Method()
{          
    // Arrange       
    var companyService = new Mock<ICompanyService>();     
    AccountController controller = new AccountController(companyService.Object);

    // Act
    var model = GetSignUpViewModel();
    var result = controller.SignUp(model);
    
    Company company = new Company();
    company.Name = model.Name;
    company.Address = model.Address;
    company.PhoneNumber = model.PhoneNumber;

    // Assert    
    companyService.Verify(x => x.Add(company));
}

If you need to test the actual data be passed to the Add method you can do this but if you just want to test whether or not the method was called regardless of the parameters supplied to the method, you can using Moq. To do this, just use It.IsAny method supplied by the Moq framework to indicate that you just want to see if the method was called with any type of Company object.

[Test]
public void SignUp_Action_Calls_CompanyService_Add_Method()
{          
    ...

    // Assert    
    companyService.Verify(x => x.Add(It.IsAny<Company>()));
}

Mocking frameworks are your friends and save hours of time if you know how to use them correctly.