I'm writing some unit tests using JUnit and JMockit and need to write a JMockit MockUp
for a method that takes an instance of a private enum as an argument. Here's the the class I need to mock:
public class Result {
//Static constants representing metrics
public static final Metric AVOIDABLE = Metric.avoidable;
public static final Metric UNAVOIDABLE = Metric.unavoidable;
// private enumeration of metric values
private enum Metric {avoidable, unavoidable};
public Long getTodayCount(Metric metric) { //<- instance of private enum
return getValueForKey(metric);
}
}
depending on the specific Metric
given I need to return a different Long
value. If the Metric
enum were public that would be straightforward enough. Something like:
private static class MockResult extends MockUp<Result> {
@Mock
Long getTodayCount(Metric m){ //<-- nope. Metric is private
if(Result.AVOIDABLE.equals(m)){ //<-- can't call equals either
return 1234L;
} else {
return 4567L;
}
}
}
But since Metric
is private is there any way to accomplish this aside from changing Metric
to be public? That may end up being the only way to accomplish this, but I'm not the author of the Result
class and am not completely familiar with the reasoning behind making Metric
private in the first place.
As per documentation:
The @Mock annotation marks those methods in the mock-up class which are meant to provide mock implementations for the corresponding methods (of the same signature) in the mocked class.
If the enum is private, you cannot use it in your unit tests as it will not be visible outside the class. Then you cannot define a proper MockUp.
You have to either make Metric
class more visible (at least package private) or mock out the whole Result
class.