Testing with mocks Top Tip – Use fields to help setup tests

Here’s a little technique I’ve picked for keeping my test code nice and clean.  Sometimes you visit a test class and it’s got mocking setup code everywhere.  Each test method setting up the mocks differently to satisfy the precondition of the test.  A simple way to reduce calls to setup is to set a field instead.  Here’s what I mean:

private AutoMock<SaveCustomerService> saveCustomerService;
private bool isValid;
public void Init()
    saveCustomerService = new AutoMock<SaveCustomerService>();
    isValid = true;
    saveCustomerService.GetMock<IValidator>().Setup(m => m.Validate()).Returns(() => isValid);
public void When_invalid_throws_exception()
    isValid = false;
public void When_valid_saves()
    isValid = true;
    var savedCustomer = Save();
    saveCustomerService.GetMock<ICustomerRepository>().Verify(r => r.Save(savedCustomer));
public Customer Save()
    var customer = new Customer();
    return customer;


The two test methods now just set isValid.  The test init method is the only guy who sets up the mock.  I think this makes the test methods much more readable.  It also helps with maintainability, because if validation changes in the future there is just one place I need to change the mock setup code.

I’m using the auto mocking class from my previous post.


About Tom Peplow

C# .Net developer based in London and the South Coast
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

One Response to Testing with mocks Top Tip – Use fields to help setup tests

  1. Pingback: A small comparison of MSpec and MSTest | pep => lowdown

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