0%

Java Mockito

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
@Slf4j
@AutoConfigureMockMvc
@SpringBootTest
@ExtendWith(SpringExtension.class)
public class ArticleRestControllerTest3 {

//mock对象
@Resource
private MockMvc mockMvc;

@MockBean
private ArticleService articleService;

//测试方法
@Test
public void saveArticle() throws Exception {

String article = "{\n" +
" \"id\": 1,\n" +
" \"author\": \"zimug\",\n" +
" \"title\": \"手摸手教你开发spring boot\",\n" +
" \"content\": \"c\",\n" +
" \"createTime\": \"2017-07-16 05:23:34\",\n" +
" \"reader\":[{\"name\":\"zimug\",\"age\":18},{\"name\":\"kobe\",\"age\":37}]\n" +
"}";

ObjectMapper objectMapper = new ObjectMapper();
Article articleObj = objectMapper.readValue(article,Article.class);

//打桩
when(articleService.saveArticle(articleObj)).thenReturn("ok");


MvcResult result = mockMvc.perform(
MockMvcRequestBuilders.request(HttpMethod.POST, "/rest/articles")
.contentType("application/json").content(article))
.andExpect(MockMvcResultMatchers.jsonPath("$.data").value("ok"))
.andDo(print())
.andReturn();

result.getResponse().setCharacterEncoding("UTF-8");
log.info(result.getResponse().getContentAsString());

}
}