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);

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.

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.


2 Responses to “Unit Testing: Verify a Method Call Ignoring the Parameters”

  1. Jef Claes Says:

    Thank you, such a time-saver.

  2. AK Says:

    How can we moq a function like this?

    public List MemberPayments(IBuildBatch bb,
    PaymentStatus Status) because it has a generic return type

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: