spring boot遇到问题一:测试代码中status(),content()等方法无法导入

网上找了篇Sping Boot的入门教程进行学习,针对某个案例编写测试代码过程中遇到了一些问题,记录如下:

HelloController类代码片段

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String index() {
        return "Hello World";
    }

}

Chapter1ApplicationTests测试类代码片段

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MockServletContext.class)
@WebAppConfiguration
public class Chapter1ApplicationTests {

    private MockMvc mvc;

    @Before
    public void setup() {
        mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
    }

    @Test
    public void getHello() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("Hello World")));
    }
}

发现status()、content()、equalTo()这些方法无法导入,经过排查,将这些方法静态导入即可,如:

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

猜你喜欢

转载自blog.csdn.net/kuangay/article/details/80875224