予期しない例外をキャッチするための次の単純なコントローラーがあります。
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler(Throwable.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ResponseEntity handleException(Throwable ex) {
return ResponseEntityFactory.internalServerErrorResponse("Unexpected error has occurred.", ex);
}
}
Spring MVC テスト フレームワークを使用して統合テストを作成しようとしています。これは私がこれまでに持っているものです:
@RunWith(MockitoJUnitRunner.class)
public class ExceptionControllerTest {
private MockMvc mockMvc;
@Mock
private StatusController statusController;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(new ExceptionController(), statusController).build();
}
@Test
public void checkUnexpectedExceptionsAreCaughtAndStatusCode500IsReturnedInResponse() throws Exception {
when(statusController.checkHealth()).thenThrow(new RuntimeException("Unexpected Exception"));
mockMvc.perform(get("/api/status"))
.andDo(print())
.andExpect(status().isInternalServerError())
.andExpect(jsonPath("$.error").value("Unexpected Exception"));
}
}
ExceptionController とモックの StatusController を Spring MVC インフラストラクチャに登録します。テスト メソッドでは、StatusController から例外をスローするように期待を設定します。
例外がスローされていますが、ExceptionController はそれを処理していません。
ExceptionController が例外を取得し、適切な応答を返すことをテストできるようにしたいと考えています。
これが機能しない理由と、この種のテストをどのように行うべきかについての考えはありますか?
ありがとう。