Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run junit test certain amount of time

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?

like image 699
dinigo Avatar asked Sep 17 '25 22:09

dinigo


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.

like image 140
Jon Skeet Avatar answered Sep 19 '25 13:09

Jon Skeet