I use Spring 5 together with Spring Boot 2. I use junit 5 for tests. I want to test error trapping in the controller (for this I have a special class), but why error trapping does not occur. My class for testing the controller:

@WebMvcTest(controllers = ExportToMsExcelController.class, secure = false) class ExportToMsExcelControllerTests { private static final String EXPORT_RESOURCE_1_URL = "/resource1/list/ms-excel"; // URL для rest-запроса по выгрузки в эксель private static final String CONTENT_TYPE = "application/vnd.ms-excel"; @Autowired private MockMvc mockMvc; @Autowired private ObjectMapper objectMapper; @MockBean private CreateXLSXDocumentService createXLSXDocumentService; /** * Тест выгрузки в файл в формате MS Excel, * входные данные: нет (search-строка не указана), * выходные данные: ошибка 500, непустой текст ошибки, * особенности: внутренний сервис вернул null * * @throws Exception любые исключительные ситуации */ @Test void exportTable_noSearchStringAndInternalServiceReturnsNull_HttpCode500AndErrorMessageReturned() throws Exception { given(createXLSXDocumentService.createXLSXDocument(anyMap())) .willReturn(null); final MvcResult mvcResult = mockMvc.perform( get(EXPORT_RESOURCE_1_URL) .accept(CONTENT_TYPE) ) .andDo(print()) .andExpect(status().isInternalServerError()) .andReturn(); final String errorMessage = mvcResult.getResponse().getErrorMessage(); assertNotNull(errorMessage, "errorMessage is null"); assertTrue(errorMessage.length() > 0, "errorMessage.length() <= 0"); } 

Class for catching errors:

 @Order(Ordered.HIGHEST_PRECEDENCE) @ControllerAdvice public class RestExceptionHandler extends ResponseEntityExceptionHandler { private final static Logger logger = LogManager.getLogger(RestExceptionHandler.class); //реализации методов абстрактного класса @ExceptionHandler({ NullPointerException.class }) public ResponseEntity<Object> handleNullPointerException(NullPointerException ex, WebRequest request) { logger.error(ex.getLocalizedMessage(), ex); return buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage(), ex, null, new ArrayList<> (Arrays.asList(ex.getStackTrace())))); } @ExceptionHandler({ IllegalArgumentException.class }) public ResponseEntity<Object> handleIllegalArgumentException(IllegalArgumentException ex, WebRequest request) { logger.error(ex.getLocalizedMessage(), ex); return buildResponseEntity( new ApiError(HttpStatus.BAD_REQUEST, ex.getMessage(), ex, null, new ArrayList<>(Arrays.asList(ex.getStackTrace()))) ); } @ExceptionHandler({ RuntimeException.class }) public ResponseEntity<Object> handleRuntimeException(RuntimeException ex, WebRequest request) { logger.error(ex.getLocalizedMessage(), ex); return buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage(), ex, null, new ArrayList<> (Arrays.asList(ex.getStackTrace())))); } @ExceptionHandler({ javax.validation.ConstraintViolationException.class }) public ResponseEntity<Object> handleConstraintViolationException(javax.validation.ConstraintViolationException ex, WebRequest request) { logger.error(ex.getMessage(), ex); String message = ex.getMessage(); return buildResponseEntity(new ApiError(HttpStatus.BAD_REQUEST, message, ex, null, new ArrayList<> (Arrays.asList(ex.getStackTrace())))); } private ResponseEntity<Object> buildResponseEntity(ApiError apiError) { return new ResponseEntity<>(apiError, apiError.getStatus()); } } 

Moreover, during the actual operation of the program, catching errors flying out of the controller works. But in the tests - no.

    1 answer 1

    Try adding context to the ExportToMsExcelControllerTests class.

     @RunWith(SpringJUintClassruner.class) @ContextConfiguration(classes={AppContext.class}) 

    or indicate the package where your context is

    • @RunWith(SpringJUintClassruner.class) not needed, it is already in @WebMvcTest . But on the context of the need to look. I use empty for everything to work, but then you need to somehow add ControllerAdvice to it - Max Lich
    • Perhaps on the topic RUnWIth you are right. I wanted to say, try to raise the context so that your ControlerAdvice is created - Parviz Rozikov
    • Well, then you need to figure out how to specify the path to the class, not the package. If it is possible. But so far, unfortunately, now there is no time to do it. Maybe I'll do something at my leisure - Max Lich