Tip #2: To make your tests more specific and focus only on the class you are testing, mock everything else.

Tip #2: To make your tests more specific and focus only on the class you are testing, mock everything else.

It is always observed that changes in one class cause other class’s tests to fail. This happens often because many other classes change when we change one class, leading to many other tests changing / breaking.

It is always best to mock all other classes. That way, other classes are not actually used in the test, and you can ensure that your tests do not break! This also ensures that the only coverage we get is from the test written for the class. Mocking helps us focus on one behavior, one class only.

This way, you also make the test very specific to the implementation details of the other classes. So, if you try to modify the structure of any other class, many more tests may fail, but then, refactoring is also a waste of time, right? (Let’s talk about it some other time!) Mocks are unrelated to the mocked class’s behavior (they adhere to structure alone and follow programmed behavior), so when the tests fail, all your team members will be left wondering why the tests always use the old code!

Moreover, mocked classes do not exhibit runtime behavior, so these will be the most brilliant ‘tests that test nothing’! All the issues will still only show up in (I love this!) production, successfully giving the team and management a false sense of security! This is called a ‘surprise test’!

Oh, I almost forgot the libraries and your database. Spinning up a DB just for the tests is a pain and slows everything down. And when the libraries change, our tests break, even when we have made no change to our code. Mocking your database and libraries ensures the ‘surprise tests’ are truly a surprise for when your code goes to production.

Heavy mocking, in fact, could be one of the best ways to convince everyone that tests are a waste of time, too!

[#CodingChaos is intentionally filled with terrible advice. Follow it at your own peril (or, for the intended effect, do the opposite)!]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.