I need to test a function that whose result will depend on current time (using Joda time's isBeforeNow()
, it so happens).
public boolean isAvailable() { return (this.someDate.isBeforeNow()); }
Is it possible to stub/mock out the system time with (using Mockito, for example) so that I can reliably test the function?
An example of a real-world scenario that could be covered by a unit test is a checking that your car door can be unlocked, where you test that the door is unlocked using your car key, but it is not unlocked using your house key, garage door remote, or your neighbour's (who happen to have the same car as you) key.
Time-dependent behavior with gel formation or curing This oscillatory test is performed under constant dynamic-mechanical conditions. Accordingly, both parameters – shear-strain (or shear-stress) amplitude and (angular) frequency – are kept constant in this test. In most cases, controlled-strain tests are preferred.
Timely: Unit tests should be written just before the production code that makes the test pass. This is something that you would follow if you were doing TDD (Test Driven Development), but otherwise it might not apply.
The best way (IMO) of making your code testable is to extract the dependency of "what's the current time" into its own interface, with an implementation which uses the current system time (used normally) and an implementation which lets you set the time, advance it as you want etc.
I've used this approach in various situations, and it's worked well. It's easy to set up - just create an interface (e.g. Clock
) which has a single method to give you the current instant in whatever format you want (e.g. using Joda Time, or possibly a Date
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With