Does stub make tests fragile?

109 Views Asked by At

suppose our SUT(Class A) has a dependency(IDependency) and we create stub with canned answer for some operations(Method A that return bool value).

in this manner we reveal some implementation details of SUT (SUT Using Method A) and if we want refactor the SUT without breaking the original behavior(instead of method A using method B that this method return bool value too).

according to Vladimir Khorikov book (unit testing) our test does not has resistant to refactor.

question is : does Stubs make tests fragile?

1

There are 1 best solutions below

2
On

As luk2302 mentioned. Test doubles (Mocks, stubs, fakes, etc ) increase the coupling between the test and the System Under Test. The aim of a unit test should be to test the behaviour, not the implementation (this was Kent Beck objective when he came up with TDD).

But sometimes it's easier and cheaper in the long term to replace a dependency. This is obvious when a dependency is one boundary of the component e.g. one would replace a class that calls an external system. On the other side, I would think twice before using a test double for a class that is in the same package to the one I'm testing; if they are in the same package it means thay are closely related and it's ok to test them together. It helps a lot to have a pure Domain Model that doesn't interact with the external world.

Also, if a test becomes more complex and it's not easy to understand, that's a sign that it might be covering too much and I need to start splitting things; adding test doubles and maybe moving production code to other classes/packages.

I want to emphasise that a SUT doesn't need to be a single class. Many people get this wrong nowadays, thinking that only a single class must be tested and mock everything else. Even the people that came up with the London/Mockist school of testing never suggested this approach of mocking everything.