Spring控制器测试路径变量给出404

问题描述

我知道这里有人问过这个问题,但我找不到答案。我有一个接受路径变量的 Spring REST 控制器端点,但我一直收到 404 而不是 200。

这是我的控制器方法

@GetMapping("/colorNames/{colorFamily}")
public ResponseEntity<List<ColorNameFamilyDTO>> getColorNamesByColorFamily(@PathVariable String colorFamily)
{
    List<ColorNameFamilyDTO> colorinformations = service.getColorNamesByColorFamily(colorFamily.toupperCase());
    
    return ResponseEntity.ok(colorinformations);
}

我的测试是:

@RunWith(springrunner.class)
@WebMvcTest(InfoController.class)
public class InfoControllerTest {
 @Autowired
 private mockmvc mockmvc;

 @MockBean
 private InfoService service;

 @Autowired
 private ObjectMapper objectMapper;

@Test
public void testGetColorNamesByFamily() throws Exception
{
    List<ColorNameFamilyDTO> colorinformations = new ArrayList<>();
    Mockito.when(service.getColorNamesByColorFamily(Mockito.anyString()))
    .thenReturn(colorinformations);
    mockmvc.perform(get("/colorNames/{colorFamily}","Blue")
            .contentType("text/plain")).andExpect(status().isOk());
}
}

我试过使用 param 并直接在路径中指定字符串。怎么了?我使用的是 SpringBoot 2.1.3.RELEASE。

添加 doPrint() 会在控制台上显示

 MockHttpServletRequest:
  HTTP Method = GET
  Request URI = /colorNames/Blue
   Parameters = {}
      Headers = [Content-Type:"text/plain"]
         Body = <no character encoding set>
  Session Attrs = {}

Handler:
         Type = com.controller.Controller
       Method = public org.springframework.http.ResponseEntity<java.util.List<com.dto.ColorNameFamilyDTO>> com.controller.getColorNamesByColorFamily(java.lang.String)

 Async:
 Async started = false
 Async result = null

Resolved Exception:
         Type = null

ModelAndView:
    View name = null
         View = null
        Model = null

FlashMap:
   Attributes = null

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

解决方法

您可以尝试使用 RequestBuilder 对象来调用控制器

 requestBuilder = MockMvcRequestBuilders.get("/colorNames/{colorFamily}","Blue")
                    .contentType(MediaType.TEXT_PLAIN_VALUE)
                    .accept(MediaType.APPLICATION_JSON_UTF8);

  mockMvc.perform(requestBuilder)
                    .andExpect(status().isOk())
                    .andDo(print())
                    .andReturn();

print() 会告诉你你正在调用哪个 api 路径

更新:

请检查控制器和测试类

@RestController
public class AddDataController {

    @Autowired
    public AddDataService addDataService;

    @GetMapping(value = "colourNames/{pathVar}")
    public ResponseEntity dataAdded(@PathVariable String pathVar){
        return addDataService.printPathVariable(pathVar);
    }
}

和测试类应该是

@WebMvcTest(AddDataController.class)
@RunWith(SpringRunner.class)
class AddDataControllerTest {

    @MockBean
    public AddDataService addDataService;

    @Autowired
    public MockMvc mockMvc;

    @BeforeEach
    public void setUp(){
        MockitoAnnotations.initMocks(this);
    }

    @Test
    void dataAdded() throws Exception {

        RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/colourNames/{pathVar}","Blue")
                .contentType(MediaType.TEXT_PLAIN_VALUE);

        mockMvc.perform(requestBuilder)
                .andExpect(status().isOk())
                .andDo(print())
                .andReturn();

    }
}

你能在这里分享 print() 响应吗

,

如果 "/colorNames" 没有端点,您将收到 HTTP 404。因此,请检查您的控制器。您的控制器类应该用 @RestController 注释标记。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...