【发布时间】:2021-02-08 06:41:23
【问题描述】:
我知道这里有人问过这个问题,但我找不到答案。我有一个接受路径变量的 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 = []
【问题讨论】: