@Slf4j
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
@SpringBootTest //单独使用@SpringBootTest不会启动servlet容器,这是就不能使用@Autowired @Resource注解
public class ArticleRestControllerTest {
//创建mockMvc这个对象来帮我们模拟请求
@Autowired
private MockMvc mockMvc;
@Test
public void saveArticle() throws Exception {
//定义发送请求要携带的请求体
String article = "{\n" +
" \"author\": \"Tom\",\n" +
" \"age\": 38,\n" +
" \"id\": 1,\n" +
" \"addr\": \"shenzhen\"\n" +
" }";
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.POST, "/rest/article")
.contentType("application/json").content(article))
//断言预期:发送请求后服务器给我们的相应状态为200
.andExpect(MockMvcResultMatchers.status().isOk())
//断言预期:响应体data.author字段的值为Tom
.andExpect(MockMvcResultMatchers.jsonPath("$.data.author").value("Tom"))
//断言预期:响应体data.age字段的值为38
.andExpect(MockMvcResultMatchers.jsonPath("$.data.age").value(38))
.andDo(print())
.andReturn();
log.info(result.getResponse().getContentAsString());
}
}
2.打桩
@Slf4j
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
@SpringBootTest //单独使用@SpringBootTest不会启动servlet容器,这是就不能使用@Autowired @Resource注解
public class ArticleRestControllerTest {
//创建mockMvc这个对象来帮我们模拟请求
@Autowired
private MockMvc mockMvc;
@MockBean
private ArticleRestService articleRestService;
@Test
public void saveArticle() throws Exception {
//定义发送请求要携带的请求体
String article = "{\n" +
" \"author\": \"Tom\",\n" +
" \"age\": 38,\n" +
" \"id\": 1,\n" +
" \"addr\": \"shenzhen\"\n" +
" }";
ObjectMapper objectMapper = new ObjectMapper();
Article article1 = objectMapper.readValue(article, Article.class);
//打桩
when(articleRestService.saveArticle(article1)).thenReturn("ok");
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.POST, "/rest/article")
.contentType("application/json").content(article))
//断言预期:发送请求后服务器给我们的相应状态为200
.andExpect(MockMvcResultMatchers.status().isOk())
//断言预期:响应体data.author字段的值为Tom
.andExpect(MockMvcResultMatchers.jsonPath("$.data.author").value("Tom"))
//断言预期:响应体data.age字段的值为38
.andExpect(MockMvcResultMatchers.jsonPath("$.data.age").value(38))
.andDo(print())
.andReturn();
log.info(result.getResponse().getContentAsString());
}
}