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?
@Test
void exceptionTesting() {
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
arrayCircleQueue.enQueue('a') ;
});
assertEquals("Queue is full now!", exception.getMessage());
}
Or you can try it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With