Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time dependent unit tests

Tags:

java

junit

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?

like image 985
pojo Avatar asked Apr 11 '11 13:04

pojo


People also ask

What is unit testing with real time example?

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.

Which is a time-dependent test?

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.

What does the timely rule of unit testing mean?

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.


1 Answers

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).

like image 128
Jon Skeet Avatar answered Oct 02 '22 03:10

Jon Skeet