This is old news, but having work with big bank and insurance companies they tend to stick with the old version of java and they’re underlying libraries, I’ve finally been expose to new ways of testing exception with junit.
I use to test exception by adding an expected right after the @Test annotation.
@Test(expected = NullpointerException)
However they’re many other ways to do that with only junit5 and mockito
Option 1: Stinking with junit4 you can define an expected exception:
@Rule
public ExpectedException bob = ExpectedException.none();
@Test
public void testShareContentFileConflict() {
bob.expect(ConflictException.class);
bob.expect(hasProperty("accountId", is(MASTER_ACCOUNT_ID)));
Mockito.when(service.getSharedId(MASTER_ID, MASTER_ACCOUNT_ID, AFFILIATE_ACCOUNT_ID)).thenReturn(null);
Mockito.when(service.shareContent(MASTER_ID, MASTER_ACCOUNT_ID, AFFILIATE_ACCOUNT_ID)).thenThrow(new ConflictException(MASTER_ACCOUNT_ID, "Error occurred"));
// call manager
String returnedAffiliateContentId = contentManager.shareContent(MASTER_ID, MASTER_ACCOUNT_ID, AFFILIATE_ACCOUNT_ID);
// validations
Assert.assertEquals(AFFILIATE_CONTENT_ID, returnedAffiliateContentId);
Mockito.verify(service).shareContent(MASTER_ID, MASTER_ACCOUNT_ID, AFFILIATE_ACCOUNT_ID);
}
Option 2: JUnit5 introduces the assertThrows method for asserting exceptions.
This takes the type of the expected exception and an executable functional interface where we can pass the code under test through a lambda expression.
@Test
public void whenExceptionIsThrown_thenAssertionSucceeds() {
Exception exception = assertThrows(NumberFormatException.class, () -> {
Integer.parseInt("1a");
});
String expectedMessage = "For input string";
String actualMessage = exception.getMessage();
assertTrue(actualMessage.contains(expectedMessage));
}
Option 3: Using mockito & assertJ:
If you’re using mokito and assertJ in your test already, there an another clean way to do it. It’s so far my favorite.
given(xxx).willThrow(new MyException())
when {() -> myService.doSomething()}
then(caughtException()).isInstanceOf(MyException.class)
They are other way to do it just with mockito using doThrow, thenThrow and spy which are explained here.
Recent Comments