Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I remove mock?

Tags:

unit-testing

Sometime back I used mocks in TDD (Test Driven Development) when the implementation of dependent interfaces was not available. So I mocked those dependencies and tested my work.

Now implementations of the dependencies are available. So should I remove the mock or should I convert them to spy or similar? I think integration tests can only be done after removing those mocks, or I may have to duplicate them. I am little confused, any suggestion on this?

like image 667
Rahul Kulshreshtha Avatar asked Nov 28 '25 12:11

Rahul Kulshreshtha


2 Answers

As far as unit tests are concerned - never. Usually it is because you want to keep your unit tests isolated:

  • Your unit tests (just as any other classes) should usually have single reason to change/break. When a bug happens you want to reduce possible number of offenders to absolute minimum. Having unit test failing because some dependency might have failed, or some other dependency might have failed, or maybe finally actual tested class might have failed is undersirable.

In reality, this is quite a strech because even changing an interface of a dependency will result in changes in unit tests of class using this dependency. What you want to avoid tho, is some guy from some other team changing implementation of some dependency you are using and as a result your tests break, apparently for no reason. This is again, highly undesirable.

Mocks should be used to isolate your units. Of course, when writing different types of tests (say integration) you don't want isolation. You want real components collaborating together. This is one of the reasons to use actual implementations rather than mocks - but! - this does not invalidate your unit tests. They should remain isolated.

like image 151
k.m Avatar answered Nov 30 '25 05:11

k.m


As always: It depends.

If you are using a mock, you are testing against a defined interface, so your unit test is more focused and there could be less breaking changes in your tests (such as when something internal needs to be refactored).

If you are using the actual dependencies, then your unit tests are not as focused (they might be integration tests). So these tests are often slower, more difficult to set up and more prone to breaking when refactoring. On the other hand, since you are testing against the actual implementation, you are more likely to find bugs due to the actual implementation behaving differently than you expected.

like image 28
Daniel Rose Avatar answered Nov 30 '25 04:11

Daniel Rose