如何在JUnit5中测试引发异常?

时间:2017-03-30 11:04:01

标签: java junit junit5

我想使用JUnit5测试异常是否正常。

例如,假设我测试队列。

public class ArrayCircleQueue {
    .
    .
    .
    public void enQueue(char item) {
        if (isFull()) {
            throw new IndexOutOfBoundsException("Queue is full now!");
        } else {
            itemArray[rear++] = item;
        }
    }
}

TestClass

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 个答案:

答案 0 :(得分:7)

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

或者你可以尝试一下。

答案 1 :(得分:-1)

在JUnit 5中,您可以使用自定义扩展名def parse(self, response): links = response.selector.xpath("/html/head/link[@rel='stylesheet']") for style_link in links: yield { 'type' : 'stylesheet', 'url' : style_link.xpath('@href') } images = response.selector.xpath("//img") for img in images: yield { 'type' : 'image', 'url' : img.xpath('@src') } java_scripts = response.selector.xpath("//script[@type='text/javascript']") for js in java_scripts: yield { 'type' : 'js', 'url' : js.xpath('@src') } 执行类似操作:

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