首页 > 解决方案 > 为什么 Spring Boot 控制器测试返回 404,但在上下文中找到控制器?

问题描述

我有一个我正在尝试测试的 REST 控制器,但是在尝试向其发布时,我得到一个 404。测试是 JUnit 5 和 Spring Boot 2.1.5。如果我运行应用程序,我可以通过 Postman 访问控制器。我已经在调试模式下运行它并验证它myController不为空并且已将模拟服务注入其中。我在这里想念什么?spring-boot-starter-test 是一个依赖项,而 junit4 是一个排除项。

@RestController
@Slf4j
@RequestMapping(path = /integrations,
    produces = "application/json")
public class MyController {

    private MyService myService;
    private MyValidationService myValidationService;

    public MyController(MySerivce service, MyValidationService myValidationService) {
        this.myService = service;
        this.myValidationService = myValidationService;
    }

    @PostMapping(path = "/users", produces = "application/json", consumes = 
                                       "application/json")
    public ResponseEntity<User> getUserList(@Valid @RequestBody final RequestPayload 
          requestPayload, @RequestHeader Map<String, String> headers) throws MyException {
        // check the credentials and permission
        Map<String, String> credInfo = myValidationService.validateHeaders(headers);

        // process payload
        return myService.retrieveUsers(requestPayload);


    }
}

测试如下:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
class MyControllerTest {

    @MockBean
    private MyService myService;

    @MockBean
    private MyValidationService myValidationService;

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    MyController myController;

    @Test
    public void contextLoads() throws Exception {
        Assert.assertNotNull(myController);
    }

    @Test
    void getUserList() throws Exception {
        List<User> users = returnUserList();
        HttpEntity<RequestPayload> requestHttpEntity = new HttpEntity<>(returnPayload(), null);
        when(myService.retrieveUsers(any(RequestPayload.class))).thenReturn(users);
        mockMvc.perform(post("/integrations/users")
                .contentType(MediaType.APPLICATION_JSON)
                .content(asJsonString(returnPayload()))
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is2xxSuccessful());

    }
}

我得到的回应是:

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = []
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

标签: javaspringspring-bootjunit5

解决方案


我很欣赏这些答案,但我发现了问题所在 - 这是一个愚蠢的问题!

事实证明,当application.properties文件中已经提供了该值时,我在 mockMvc 调用中包含了上下文路径!因此,使用的真正 URI 不是/integrations/users的 URI,而是/integrations/integrations/users,这并不奇怪!

感谢所有人,很抱歉没有把我的眼睛放在我的手中并仔细观察。


推荐阅读