I’ve got a piece of code like this:
class Lekcja {
Calendar _date;
public Lekcja() {
_date = Calendar.getInstance();
}
public Calendar getDate() {
return _date;
}
}
And I want to test it using JUnit4 and Mockito, instead of using real Calendar object I want to put a mock object there. Could you please tell me how to do it?
Mocking value objects is rarely a good idea. You should mock behaviour, not data. I guess what you really want to achieve is to be able to use arbitrary date in tests (which is a good idea).
The pattern I am using successfully in such cases is a fake system clock (examples from that site):
And two implementations, real:
and fake for testing:
I find it convenient to make
currentTimeMillis()static in a helper method and usestaticfield pointing to currentTimeSource.Finally, much simpler approach is to pass the date directly:
See also