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

0dxa2lsx  于 2021-07-23  发布在  Java
关注(0)|答案(2)|浏览(476)

我知道这里有人问过这个问题,但我找不到答案。我有一个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 还可以直接指定路径中的字符串。怎么了?我使用的是springboot2.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 = []
jum4pzuy

jum4pzuy1#

如果“/colornames”没有端点,您将得到http404。因此,检查控制器。控制器类应标记为@restcontroller注解。

w51jfk4q

w51jfk4q2#

您可以尝试使用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()的回应吗

相关问题