I'm writing a test case to test an object behaviour.
When the object is instantiated it must allow the call of a method let say call() only if it has been called within 500 ms, otherwise it must throw an exception.
I designed the Junit test case like this:
@Test(expected = IllegalStateException.class)
public void testCallAfterTimeout() {
MyObject o= new MyObject();
//To ensure the timeout is occurred
Thread.sleep(1000);
o.call();
}
Do you think is a good practice or I should follow another approach?
Many thanks
There are two problems with using (real) time in test cases:
Thread.sleep()
with in a multithreaded test case this is even more difficult.If you must, your way is acceptable. But there are other options:
Don't use a real clock. Instead use a fake (mocked/stubbed) clock that you can control from your testcase:
@Test(expected = IllegalStateException.class)
public void testCallAfterTimeout() {
MyObject o= new MyObject();
// Example function that you could make
advanceClock(1000, TimeUnit.MILLISECONDS)
o.call();
}
In your object you have to inject a clock. MyObject
could look like this:
class MyObject
{
public MyObject()
{
this(new Clock());
}
// Protected so only the test case can access it
protected MyObject(Clock clock)
{
// Save clock as local variable, store creation time etc.
}
}
In Java 8 a mechanism for this is provided, see for instance LocalDate.now()
. But you can also implement your own quiet easily.
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