如何在JUnit5中测试抛出异常?

4
我想使用JUnit5测试异常是否正常工作。例如,假设我测试队列。
public class ArrayCircleQueue {
    .
    .
    .
    public void enQueue(char item) {
        if (isFull()) {
            throw new IndexOutOfBoundsException("Queue is full now!");
        } else {
            itemArray[rear++] = item;
        }
    }
}

测试类

class ArrayCircleQueueTest {
    .
    .
    .
    @org.junit.jupiter.api.Test
    void testEnQueueOverflow() {
        for (int i=0; i<100; i++) {
            queue.enQueue('c');  # test for 10-size queue. It should catch exception
        }
    }
}

我在谷歌上搜索了相关内容,但是只找到了JUnit4的答案:

@Test(expected=NoPermissionException.class)

但是这种方式在JUnit5上无法使用。

我该如何解决这个问题?

2个回答

9
@Test
void exceptionTesting() {
    Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
        arrayCircleQueue.enQueue('a') ;
    });
    assertEquals("Queue is full now!", exception.getMessage());
}

或者你可以尝试一下。

-1
在JUnit 5中,您可以通过自定义TestExecutionExceptionHandler扩展来执行类似的操作:
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
import org.junit.jupiter.api.extension.TestExtensionContext;

public class HandleExtension implements TestExecutionExceptionHandler {

    @Override
    public void handleTestExecutionException(TestExtensionContext context,
            Throwable throwable) throws Throwable {
        // handle exception as you prefer
    }

}

然后在你的测试中,你需要使用ExtendWith声明该扩展:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

public class ExceptionTest {

    @ExtendWith(HandleExtension.class)
    @Test
    public void test() {
        // your test logic
    }

}

一个自定义的 TestExecutionExceptionHandler 当然可以工作,但只有在您将逻辑重用于整个测试套件时才真正有意义。然而,在一次性情况下,推荐使用 assertThrows(...) 方法。 - Sam Brannen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接