春季测试返回404

时间:2020-03-09 14:46:26

标签: spring-boot

针对Spring Boot REST控制器运行JUnit测试时出现异常。我通过Postman测试了API,并且可以正常工作。不知道我在JUnit测试中缺少什么。

这是我的控制器:

@RestController
@RequestMapping(value = "/api/v1/app/detail",
        produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
        consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class AppTestController {

@Reference(timeout = 60000, check = false)
private IAppRpcService appRpcService;
@Reference(timeout = 60000, check = false)
private IAlarmService alarmRpcService;
@Autowired
private ApplicationService applicationService;



@PostMapping("state")
public AppState getAppState(@RequestBody AppQueryVO vo) {
    if (isEmpty(vo) || isEmpty(vo.getAppId())) {
        throw RiilExceptionUtils.bizException(null, PARAM_ERROR,
                PARAM_ERROR_MSG);
    }
    return applicationService.getAppState(vo.getAppId());
} 

这是我的测试用例,无论我刚刚返回404:

    @Slf4j
    @RunWith(SpringRunner.class)
    @WebMvcTest(value = AppTestController.class, secure = false)
    //@RunWith(SpringRunner.class)
    //@SpringBootTest
    @AutoConfigureMockMvc
    public class TestControllerTest {
        @Autowired
        private MockMvc mockMvc;
        @MockBean
        private ApplicationService service;

    private ResultHandler logHandler = result -> {
        MockHttpServletRequest request = result.getRequest();
        String url = request.getRequestURI();
        String contentAsString = request.getContentLength() > 0 ? request.getContentAsString() : "";
        log.info("mvc:\n{}\n>{}\n<{}", url, contentAsString,
                result.getResponse().getContentAsString());
    };


    @Test
    public void testState() throws Exception {

        AppQueryVO vo = new AppQueryVO();
        vo.setAppId("eb8db69a-f3ec-11e9-8dff-02420a0a0a05");
        this.mockMvc.perform(
                post("/api/v1/app/detail/state")
                        .contentType(MediaType.APPLICATION_JSON_UTF8)
                        .content(JSON.toJSONString(vo))
        ).andDo(logHandler).andExpect(status().isOk());

    }
}

0 个答案:

没有答案