Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial Mocking As Code Smell?

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?

like image 540
Nelz Avatar asked Sep 27 '10 19:09

Nelz


People also ask

Is mocking a code smell?

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.

Is mocking an Antipattern?

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.

Why mocking is not good?

Mocking is bad because it can lead to overspecification of tests. Use stub if possible and avoid mock.

What is a code smell in programming?

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.


Video Answer


1 Answers

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.

like image 105
emulcahy Avatar answered Sep 25 '22 02:09

emulcahy