问题
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:
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.
来源:https://stackoverflow.com/questions/15262820/run-junit-test-certain-amount-of-time