Your problem is actually that getClass
is final
in Object
, so you can't stub it with Mockito. I can't think of a good way around this. There is one possibility, that you might consider.
Write a utility class that has a single method
public Class getClass(Object o){
return o.getClass();
}
and refactor the class that you're testing, so that it uses an object of this utility class, instead of calling getClass()
directly. Then, make it possible to inject the utility object, either with a special package-private constructor, or with a setter method.
public class ClassToTest{
private UtilityWithGetClass utility;
private Map<Class<?>, Object> map = new HashMap<Class<?>, Object>();
public ClassToTest() {
this(new UtilityWithGetClass());
}
ClassToTest(UtilityWithGetClass utility){
this.utility = utility;
// Populate map here
}
// more stuff here
}
Now, in your test, make a mock of the object and stub getClass
. Inject the mock into the class that you're testing.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…