I want to test something for a while, say 5 seconds, and then pass the test if nothing wrong has been asserted. Is this possible with annotations? Can something like @Test(uptime=5000)
be used?
1 Answers
Revised answer after question was edited
Fundamentally it feels like you're testing the wrong thing here - it seems very odd for "nothing happening" to be a sign of success.
If you want to prove that your algorithm can run for a certain amount of time without failing, I would actually extract out a single cycle, then write a test of something like:
@Test
public void fineForFiveSeconds() {
long start = System.nanoTime();
long end = start + TimeUnit.SECONDS.toNanos(5);
while (System.nanoTime < end()) {
test.executeOneIteration();
}
}
This way you don't have a separate thread which has to kill the working code, etc.
Original answer
This answer was written before the question indicated that timing out was a sign of success, not failure.
I think you just want the timeout
attribute in the @Test
annotation:
@Test(timeout = 5000)
with documentation:
Optionally specify timeout in milliseconds to cause a test method to fail if it takes longer than that number of milliseconds.

- 1,421,763
- 867
- 9,128
- 9,194
-
Just for clarification, this just fails the test, the thread in which the test method is running is still running, until the JVM is stopped of course. – Matthew Farwell Mar 07 '13 at 18:22
-
I haven't explained myself very well. I want to run for a certain amount of time and if nothing happens then pass the test. – dinigo Mar 08 '13 at 03:19
-
1@demil133: That's a *very* strange requirement - the exact opposite of what I'd normally expect. Normally code not completing in time is a sign of *failure*, not success. Do you really want an implementation of `while (true) {}` to be successful? – Jon Skeet Mar 08 '13 at 03:24
-
@JonSkeet: Thanks for the hint. Maybe it's my point of view what's wrong. I'll try different approximation to the test. – dinigo Mar 08 '13 at 03:27
-
@demil133: I've edited my answer to indicate a possible approach, but it's still odd :) – Jon Skeet Mar 08 '13 at 03:30