Some Thoughts on Mocking

 

Magritte Pipe
Credit: Wikipedia

 

When do we use mocks and when shouldn’t we? Some thoughts:

Don’t Mock Data Structures

We wouldn’t mock an NSArray or an NSDictionary, so why would we mock our own data structures? Data structures should be simple and well tested, so we can trust them to behave as they should. It will be more work to mock them than just to use them.

Mock Behaviour, Not State

If we did decide to mock a data structure, we’d have to specify all the interactions between the mock and the code. That would make our tests more verbose.

More importantly, the relevant thing isn’t how the data structure is used (the behaviour), but what happens given the state.

Combining This

We use mocks when we have a complex object that we want to control. For example, we’d use a mock for things where we can’t set the state. So for instance, we might want a mock to return a fake location or return that the device has a camera (even though the simulator doesn’t have a camera). If we used a mock to return a fake location, we would return a real location object (which we can create with whatever data we want), but through a mock.

 

If you found this interesting, I’ve covered testing iOS apps in more detail in this workshop – there’s a sample app and a guide that takes you step by step through adding tests.

3 thoughts on “Some Thoughts on Mocking

Leave a Reply