4

I want to test whether exception works well or not using JUnit5.

For example, let say I test queue.

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
        }
    }
}

I search it in google, but there are only answer for JUnit4: @Test(expected=NoPermissionException.class)

but it doesn't work on JUnit5.

How can I deal with it?

user3595632
  • 5,380
  • 10
  • 55
  • 111

2 Answers2

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

Or you can try it.

aggredi
  • 406
  • 3
  • 11
-1

In JUnit 5 you can do similar things with a custom extension of 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
    }

}

Then in your test, you need to declare that extension with 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
    }

}
Boni García
  • 4,618
  • 5
  • 28
  • 44
  • A custom `TestExecutionExceptionHandler` certainly works but really only makes sense if you will reuse the logic across your test suite. For the one-off case, however, `assertThrows(...)` is the recommended approach. – Sam Brannen Apr 06 '17 at 15:32