0

I can not pass the test with MockMvc in my Spring Boot application.

My ControllerAdvice looks like:

@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());

    }
}

and I have two test :

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

In this case when I have setup() commented test getRunsTestCorrectValues() passed and getRunsTestRunsNotFoundException() failed with:

enter image description here

In second case when I will uncomment setup() and re-run test I got getRunsTestCorrectValues() failed and getRunsTestRunsNotFoundException() passed with:

enter image description here

I think is something related with setup(). Does someone has any ideas?

4

1 回答 1

1

当你模拟 runService时,你应该简单地保留你的测试用例,所以你应该像这样修改第二个,以便抛出异常。

given(runService.getRuns()).willThrow(new RunNotFoundException("Not Found"));
于 2020-04-19T16:19:53.147 回答