After reading Martin Fowler's Mocks Aren't Stubs, I've discovered I've been practicing TDD in the "mockist" fashion.
But I'm wondering if even in mockist TDD if one can take mocking too far.
Here's an updated example in Python-style pseudo-code:
def sync_path(self):
if self.confirm_or_create_connection():
self.sync(self.dirpath)
The confirm_or_create_connection() method creates a connection to a server.
I tested a method similar to this in two tests, both of which mock confirm_or_create_connection() and sync() (even though they're both methods in the same class). In one test the mock confirm_or_create_connection() returns True and the test confirms that sync() was called, and in the other the mock confirm_or_create_connection() returns False and the test confirms that sync() was not called.
Is this reasonable? Or should I mock the objects that confirm_or_create_connection() and sync() call? (I have other tests of both of these methods that already do this.)
Please don't answer the question by explaining that I should be practicing "classical" TDD instead. That's an answer to another question: Should I practice mockist or classical TDD?
Fakes are generally used to improve performance by avoiding external calls. Mocks are used to verify the behavior of our code. Stubs are used to provide data that our code needs to run. We should use the simplest test double that will get the job done.
Mocking is the creation of an object that mimics another and sets expectations concerning its behavior. In testing, mocking replicates the behavior of a service, object, or process. There are a number of benefits that result from replacing an object with a mock for testing purposes.
Mocking and stubbing of internal functions Mocks and stubs are very handy for unit tests. They help you to test a functionality or implementation independently, while also allowing unit tests to remain efficient and cheap, as we discussed in our previous post.
Mocks use behaviour verification. Classical uses state verification. I generally prefer the classical style to the mocking mostly because I don't like thinking about implementation when writing a test.
The technique is called "mock objects", not "mock methods" for a reason. It encourages designs that divide the system into easily composed, collaborating objects and away from procedural code. The aim is to raise the level of abstraction so that you mostly program by composing objects and rarely write low-level control flow statements.
Personally I think that mocking on self is almost always a code smell. It's testing the implementation rather than the behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With