Say you have a property startTime
. Then you have a method doSomething
:
doSomething() {
//...stuff
startTime = System.currentTimeMillis();
//... more stuff
}
How do you test that startTime
was assigned correctly? You can't test against an absolute timestamp – it'll likely change between assignment and test. Maybe use a range?
Best Answer
One simple way is to pass in the time from outside the method:
Your production code that calls the method can pass in the real value for System.currentTimeMillis(), whereas your unit test(s) can pass in a specific known value.
Of course, this isn't quite the same as your original. Another possibility that is a little more complex but should mimic the behaviour of your of your original more closely:
Define the interface:
Two implementations, one for the production code:
One for the unit tests:
Instantiate an ITimeGetter appropriate to your scenario and pass it in to the method you want to test.