Partial Mocks are bad, why exactly?
Scenario
I have a class call it Model that represents a complex, composite object
of many other objects of varying types and purposes.
I have a Metrics class which calculates some more or less complex metrics
about the Model, in essence it looks something like this:
public class Metrics{
private final Model model;
public Metrics(Model aModel){model = aModel;}
public double calculateSimpleMetric1(){...}
public double calculateSimpleMetric2(){...}
public double calculateSimpleMetricN(){...}
public double calculateComplexMetric(){
/* Function that uses calls to multiple calculateSimpleMetricX to
calculate a more complex metric. */
}
}
I have already written tests for the calculateSimpleMetricX functions and
each of them require non-trivial, but manageable amounts (10-20 lines) of
setup code to properly mock the related parts of the Model.
Problem
Due to the unavoidable complexity of the Model class stubbing/mocking all
the dependencies for calculateComplexMetric() would create a very large
and difficult to maintain test (over 100 lines of setup code to test a
reasonable representative scenario, and I need to test quite a few
scenarios).
My thought is to create a partial mock of Model and stub the relevant
calculateSimpleMetricX() functions to reduce the setup code to a
manageable 10 or so lines of code. As these functions are already tested
separately.
However, Mockito documentation states that partial mocks are a code smell.
Question
Personally I would cut the corner here and just partial mock the Metrics
class. But I'm interested in knowing what is the "purist" way to structure
this code and unit test?
No comments:
Post a Comment