MockMvc测试返回404而不是200,而url中没有前导“/”

时间:2018-01-12 17:14:14

标签: spring spring-mvc spring-boot mockmvc

Spring Boot 1.5.9及以下版本:

@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@SpringBootTest
public class BigPoolControllerMockMvcTest {

    @Autowired
    private MockMvc mockMvc;

    @Before
    public void initialize() {
    }

    @Test
    public void testGetDisplayPools() throws Exception {
        this.mockMvc.perform(get(CONTROLLER_PATH + DISPLAY_POOLS_API + "?param=abc")
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andDo(print()).andExpect(status().isOk());
    }


}

我一直在: 警告o.s.web.servlet.PageNotFound - 在名为“

的DispatcherServlet中找不到具有URI [api / v1 / app / pool]的HTTP请求的映射

1 个答案:

答案 0 :(得分:0)

结果显示URL需要以“/”开头,以便mockmvc请求找到它:

  @Test
    public void testGetDisplayPools() throws Exception {
        this.mockMvc.perform(get("/" + CONTROLLER_PATH + DISPLAY_POOLS_API + "?amazonRegionCode=us-west-1")
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andDo(print()).andExpect(status().isOk());
    }

领先的“/”有效。感谢这篇文章:https://blmte.com/computer-internet-technology/2416430_spring-test-returning-404-instead-of-200-in-testing-rest-api-in-spring-boot