Ho il seguente controller semplice per raccogliere eventuali eccezioni impreviste:Metodo di prova Spring MVC @ExceptionHandler con Spring MVC prova
@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);
}
}
Sto cercando di scrivere un test di integrazione utilizzando il framework Spring MVC test. Questo è quello che ho finora:
@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"));
}
}
io registrare l'ExceptionController e un finto StatusController nell'infrastruttura Spring MVC. Nel metodo di test ho impostato un'aspettativa per generare un'eccezione da StatusController.
È stata generata un'eccezione, ma EccezioneController non ha a che fare con esso.
Desidero poter verificare che ExceptionController ottenga eccezioni e restituisca una risposta appropriata.
Qualche idea sul perché questo non funziona e come dovrei fare questo tipo di test?
Grazie.
Immagino che nel test i gestori di eccezioni non vengano assegnati, non so perché esattamente ma questo è il motivo per cui accade, guarda questa risposta http: // stackoverflow. it/questions/11649036/exceptionhandler-not-working-with-spring-mvc-3-1-unit-test – engma
Qualche notizia a riguardo? Sono nella stessa situazione. – Cemo
Non ho trovato una soluzione. Ho deciso che mi sarei fidato di @ExceptionHandler e visto che il metodo è semplice ho deciso che potrei vivere senza testare quell'annotazione. È ancora possibile testare il metodo con un test unitario regolare. – C0deAttack