如何在测试(junit)中为块设置超时?

时间:2014-12-15 13:42:40

标签: java junit timer timeout stopwatch

我想将测试中的某个块限制为1秒。

我试过这个:

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

但是编译器要求使用try-catch包装run()正文。

我想把这个异常抛在main()方法中 (并返回结果代码3)

我该怎么做?

1 个答案:

答案 0 :(得分:1)

不要抛出TimeoutException,而是抛出自己的Exception来扩展RuntimeException。

请注意,这将终止您的计时器线程。如果这是一个问题,请使用ScheduledExecutorService