spring boot 单元测试使用new MockMvc和@RunWith+@AutoConfigureMockMvc注解的区别
2021-02-09 16:18
标签:inf 而在 依赖注入 依赖 eth auto red ica 使用 在单元测试中用以上两种都能实现,但是@RunWith注解还可以实现代码中的依赖注入(前者不能) 不会报出异常 spring boot 单元测试使用new MockMvc和@RunWith+@AutoConfigureMockMvc注解的区别 标签:inf 而在 依赖注入 依赖 eth auto red ica 使用 原文地址:https://www.cnblogs.com/zhoushiya/p/12748777.html单测代码如下
Slf4j
@RestController
@RequestMapping("/rest")
public class ArticleRestController {
@Resource
ArticleRestService articleRestService;
/**
* 增加一篇文章
*
* @param article
* @return
*/
// @RequestMapping(value = "/article", method = RequestMethod.POST, produces = "application/json")
@PostMapping("/article")
public AjaxResponse saveArticle(@RequestBody Article article) {
articleRestService.saveArticle(article);
return AjaxResponse.success(article);
}
}
自定义MockMvc做法,会报出空指针异常
@Slf4j
@SpringBootTest
public class ArticleRestControllerTest {
//mock对象
private MockMvc mockMvc;
//mock对象初始化
@BeforeEach
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(new ArticleRestController()).build();
}
//测试方法
@Test
public void saveArticle() throws Exception {
String article = "{\n" +
" \"id\": 1,\n" +
" \"author\": \"zimug\",\n" +
" \"title\": \"手摸手教你开发spring boot\",\n" +
" \"content\": \"c\",\n" +
" \"reader\":[{\"name\":\"zimug\",\"age\":18},{\"name\":\"kobe\",\"age\":37}]\n" +
"}";
MvcResult result = mockMvc.perform(
MockMvcRequestBuilders.request(HttpMethod.POST, "/rest/article")
.contentType("application/json").content(article))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.data.author").value("zimug"))
.andExpect(MockMvcResultMatchers.jsonPath("$.data.reader[0].age").value(18))
.andDo(print())
.andReturn();
log.info(result.getResponse().getContentAsString());
}
}
使用@RunWith(SpringRunner.class)注解
@Slf4j
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc //相当于new MockMvc
@SpringBootTest
public class ArticleRestControllerTest2 {
//mock对象
@Resource
private MockMvc mockMvc;
@Resource
ArticleRestService articleRestService;
//测试方法
@Test
public void saveArticle() throws Exception {
String article = "{\n" +
" \"id\": 1,\n" +
" \"author\": \"zimug\",\n" +
" \"title\": \"手摸手教你开发spring boot\",\n" +
" \"content\": \"c\",\n" +
" \"reader\":[{\"name\":\"zimug\",\"age\":18},{\"name\":\"kobe\",\"age\":37}]\n" +
"}";
MvcResult result = mockMvc.perform(
MockMvcRequestBuilders.request(HttpMethod.POST, "/rest/article")
.contentType("application/json").content(article))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.data.author").value("zimug"))
.andExpect(MockMvcResultMatchers.jsonPath("$.data.reader[0].age").value(18))
.andDo(print())
.andReturn();
log.info(result.getResponse().getContentAsString());
}
}
解析
文章标题:spring boot 单元测试使用new MockMvc和@RunWith+@AutoConfigureMockMvc注解的区别
文章链接:http://soscw.com/index.php/essay/53168.html