Why is there so much hating going on about 'partial mocking' and the code that requires it?
Here's an (theoretical) example implementation:
public ComplexResult1 operationA(Stimulus a) {
{
...
result = ...;
}
auditTheChange(a);
}
public ComplexResult2 operationB(Stimulus b) {
{
...
result = ...;
}
auditTheChange(b);
return result;
}
void auditTheChange(Stimulus stim) {
// do a bunch of stuff to record the change
// and interact with another outside service
}
Now, in my understanding this is well refactored code.
If I want to UNIT test operationA and operationB, and ensure that auditing happens in each scenario, but without having to test the specifics of the audit code, I would use partial mocking.
What am I not seeing/understanding that causes so many projects (EasyMock, Mockito, etc.) to recommend refactoring?
I frequently tell people that mocking is a code smell, but most developers pass through a stage in their TDD skills where they want to achieve 100% unit test coverage, and can't imagine a world in which they do not use mocks extensively.
Overusing mocks can be an antipattern, not mocking itself. It's true that you need to mock/stub your dependencies, but when your class has too many dependencies, it can take more time and effort to mock and wire up everything correctly than to write the class itself.
Mocking is bad because it can lead to overspecification of tests. Use stub if possible and avoid mock.
Put simply, code smells are a result of poor or misguided programming. These blips in the application code can often be directly traced to mistakes made by the application programmer during the coding process. Typically, code smells stem from a failure to write the code in accordance with necessary standards.
If auditing is truly an internal function of the class then the code should be tested as part of the unit test. Why does your class handle both complex operations and auditing? Could the auditing be moved to a separate class?
If so, introduce the auditing as a collaborator with this class and mock it out. If not, unit test it.
You can use partial mocks, but in this case I think it is an indication the class is doing too much.
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