@RunWith(SpringRunner.class)
@SpringBootTest(classes = net.seehope.security.demo.DemoApplication.class)
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
MockMvcBuilders.webAppContextSetup(context).build();
构建MockMvc
@Before
public void setUp(){
mockMvc= MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void whenQueryAllUserSuccess() throws Exception {
//输入测试API
String result=mockMvc.perform(MockMvcRequestBuilders.get("/test/getUser")
//MediaType指的是要传递的数据的MIME类型,MediaType对象包含了三种信息:type 、subtype以及charset
.contentType(MediaType.parseMediaType("application/json"))
//向API传入变量
.param("username","wxb")
.param("password","asd")
)
//规定响应数据的结果
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(5))
.andExpect(MockMvcResultMatchers.jsonPath("$[0].username").value("username0"))
.andReturn().getResponse().getContentAsString();
//输出测试结果
System.out.println(result);
}
评论