Search code examples
javajunitjunit5

JUnit 5 Exception Testing Equivalent of Junit 4


I have the following JUnit 4 test for exception:

@Test(expected = NotFoundException.class)
public void getRecipeByIdTestNotFound() throws Exception {

    Optional<Recipe> recipeOptional = Optional.empty();

    when(recipeRepository.findById(anyLong())).thenReturn(recipeOptional);

    Recipe recipeReturned = recipeService.findById(1L);

    //should go boom
}

I want help on the most efficient approach to test the same in JUnit 5.


Solution

  • Usage 1:

    try{
        Optional<Recipe> recipeOptional = Optional.empty(); 
        when(recipeRepository.findById(anyLong())).thenReturn(recipeOptional); 
        Recipe recipeReturned = recipeService.findById(1L);
    }catch(Exception e){
        AssertThat(e, instanceOf(NotFoundException.class));
    }
    

    Usage 2:

    Assertions.assertThrow(NotFoundException.class, () -> {
        Optional<Recipe> recipeOptional = Optional.empty();
        when(recipeRepository.findById(anyLong())).thenReturn(recipeOptional);
        Recipe recipeReturned = recipeService.findById(1L);
    });