Search code examples
javajunittimertimeoutstopwatch

how can I set a timeout to a block in a test (junit)?


I want to limit a certain block in a test to 1 second.

I have tried this:

    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            throw new TimeoutException("test time: expected:"+expectedTimeMilli);
        }
    } ;
    new Timer().schedule(timerTask, 1L);

but the complier asks to wrap the run() body with try-catch.

I want to throw this exception to be caught in main() methd (and return result code 3)

how can I do this?


Solution

  • Rather than throwing TimeoutException, have it throw your own Exception that extends RuntimeException.

    Note that this will kill your timer thread. If this is an issue, use ScheduledExecutorService