Sometimes our methods throw exceptions and we want to mock the object and test the exceptions. We can use Mockito mock objects with when()
and thenThrow()
to mock this scenario.
Mockito Stub Exception – JUnit 5
Let’s see a simple example where we will mock our object method to throw an exception. Then we will use JUnit 5 assertThrows
to test the exception and its message.
package com.journaldev.mockito.examples;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.jupiter.api.Test;
class JUnitMockitoStubExceptions {
@SuppressWarnings("unchecked")
@Test
void test() {
List<String> list = mock(List.class);
when(list.size()).thenThrow(new RuntimeException("size() method not supported"));
Exception exception = assertThrows(RuntimeException.class, () -> list.size());
assertEquals("size() method not supported", exception.getMessage());
}
}
For simplicity, I am mocking List interface. Similarly, we can mock any other object too and specify its behavior to throw an exception when a specific method is called.
Mockito Stub Exception – TestNG
If you are using TestNG framework, then we can use assertThrows
assertion.
@Test
void test() {
List<String> list = mock(List.class);
when(list.size()).thenThrow(new RuntimeException("size() method not supported"));
assertThrows(RuntimeException.class, () -> list.size());
}
If we want to test exception message too, then we can use @Test annotation expectedExceptions
and expectedExceptionsMessageRegExp
attributes.
@Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "size method not supported")
void test1() {
List<String> list = mock(List.class);
when(list.size()).thenThrow(new RuntimeException("size method not supported"));
list.size();
}