JUnit 5异常测试JUnit 4的等效项

sqxo8psd  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(174)

我有下面的JUnit 4异常测试:

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

我希望得到有关在JUnit 5中测试相同内容的最有效方法的帮助。

7kqas0il

7kqas0il1#

用法一:

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

用法二:

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

相关问题