- 在test类的上面添加@RunWith(SpringRunner.class),@SpringBootTest两个注解
- 将WebApplicationContext注入到类中
@Autowired
private WebApplicationContext webApplicationContext;
- 创建一个MockMvc对象并编写初始化方法
@BeforeEach
public void setup() {
System.out.println("实例化mockmvc");
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
这里注意一下@BeforeEach注解,在以前的版本使用的是@Before,在spring boot 2.0以后就不能使用了
- 创建方法并在方法上面添加@Test注解
@Test
public void whenQuerySuccess() throws Exception {
//下面的get是根据你所需要发的请求方式而定的,有post,put,delete
String contentAsString = mockMvc.perform(MockMvcRequestBuilders.get("/user")
//用来添加参数
.param("username", "jojo")
//设置返回的json编码
.contentType(MediaType.APPLICATION_JSON))
//添加测试类的期望下面这个是希望返回的状态码是200
.andExpect(MockMvcResultMatchers.status().isOk())
//接受返回的json数据并转换为String
.andReturn().getResponse().getContentAsString();
System.out.println(contentAsString);
}
运行test方法就ok了