为什么 Spring 启动控制器测试返回 404,但在上下文中找到控制器?

Why Spring Boot controller test returning 404, but controller found in context?

我有一个我正在尝试测试的 REST 控制器,但是在尝试 POST 时,我得到了 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 = []

您可以改用切片测试注释。要测试控制器,您可以使用@WebMvcTest。

您的设置如下所示:

@SpringBootTest(value = MyController.class)
@ExtendWith(SpringExtension.class)
class MyControllerTest { 

您仍然可以@Autowired MockMvc。也不需要在测试中自动连接你的控制器。

感谢您的回答,但我发现了问题所在 - 这是一个愚蠢的问题!

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

谢谢大家,很抱歉没有把我的眼睛放在手上仔细看。