Hiding class (static) methods doesn't work quite the same as Overriding instance methods. To prove that JMock is not to blame here, try this:
public class test3 {
public static void main(String[] args) {
Owner owner = new Owner();
owner.getThing().method(); //Like how you execute your test
RealThing thing = new RealThing();
thing.method(); //Similar to your mock.
}
private static class Owner {
private BaseThing thing = new RealThing();
public BaseThing getThing() {
return thing;
}
}
private static class BaseThing {
public static void method() {
System.out.println("Basething!");
}
}
private static class RealThing extends BaseThing {
public static void method() {
System.out.println("Realthing!");
}
}
}
Note that the two calls to method()
print different things! Both are instances of RealThing, but they call different methods. The static method called depends on whether it is called from the subcalss or the superclass. In the first call above, method is declared as a BaseClass, so BaseClass.method()
is called, even though it is an instance of RealClass. The second call to method()
is declared as a RealClass, so RealClass.method()
is invoked.
So, the results from JMock are valid. The method()
called was not the same as the one you set up an expectation for.
Don't feel great about my explanation of this. Please do read up on it here: http://docs.oracle.com/javase/tutorial/java/IandI/override.html
The fix (favoring BaseThing.method()
), change:
final RealThing thing = mockery.mock(RealThing.class, "thing");
To:
final BaseThing thing = mockery.mock(RealThing.class, "thing");
Or if you prefer to use RealThing.method()
, change:
owner.getThing().method()
To:
RealThing thing = (RealThing)owner.getThing();
thing.method();