Тестирование @ControllerAdvice с ошибкой Mock Mvc Http Status - PullRequest
0 голосов
/ 19 апреля 2020

Я не могу пройти тест с Mock Mvc в моем приложении Spring Boot.

Мой ControllerAdvice выглядит так:

@ControllerAdvice
@Slf4j
public class ExceptionHandlers extends BaseExceptionHandler {

    public ExceptionHandlers() {
        super(log);
    }

    @ResponseBody
    @ExceptionHandler(RunNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ErrorResponse handleRunNotFoundController(final RunNotFoundException ex) {
        log.error("Run not found thrown", ex);
        return new ErrorResponse(LocalDateTime.now(), "RUN_NOT_FOUND", ex.getMessage(), HttpStatus.NOT_FOUND.value());

    }
}

, и у меня есть два теста:

@RunWith(SpringRunner.class)
@WebMvcTest(RunController.class)
public class RunControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private RunService runService;

//    @Before
//    public void setup() {
//        this.mvc = MockMvcBuilders.standaloneSetup(runService)
//                .setControllerAdvice(new ExceptionHandlers())
//                .build();
//    }

    @Test
    public void getRunsTestCorrectValues() throws Exception {

        List<Run> list = prepareRunList();
        when(runService.getRuns()).thenReturn(list);

        mvc.perform(get("/api/runs")
                .contentType("application/json"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(1)))
                .andExpect(jsonPath("$[0]").exists())
                .andExpect(jsonPath("$[0]").isNotEmpty())
                .andExpect(jsonPath("$[0].id").value(1))

    }

    @Test
    public void getRunsTestRunsNotFoundException() throws Exception {
        given(runService.getRuns()).willReturn(Collections.emptyList());

        mvc.perform(get("/api/runs")
                .contentType(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isNotFound());
    }
}

В этом случае, когда я setup() прокомментировал тест getRunsTestCorrectValues(), пройденный и getRunsTestRunsNotFoundException() не удалось с:

enter image description here

Во втором случае, когда я раскомментирую setup() и перезапущу тест, я получил getRunsTestCorrectValues(), и неудача и getRunsTestRunsNotFoundException() передано с:

enter image description here

Я думаю, что-то связано с setup(). У кого-нибудь есть идеи?

1 Ответ

1 голос
/ 19 апреля 2020

Когда вы высмеиваете runService , тогда вы должны просто сохранить свои тестовые случаи, поэтому вы должны изменить второй пример следующим образом, чтобы вызвать исключение.

given(runService.getRuns()).willThrow(new RunNotFoundException("Not Found"));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...