在單元測試中用以上兩種都能實現,但是@RunWith注解還可以實現代碼中的依賴注入(前者不能)
單測代碼如下
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());
}
}
不會報出異常
解析
- RunWith方法為我們構造了一個的Servlet容器運行運行環境,並在此環境下測試。然而為什么要構建servlet容器?因為使用了依賴注入,注入了MockMvc對象,而在上一個例子里面是我們自己new的。
- 而@AutoConfigureMockMvc注解,該注解表示 MockMvc由spring容器構建,你只負責注入之后用就可以了。這種寫法是為了讓測試在Spring容器環境下執行。
- Spring的容器環境是什么呢?比如常見的 Service、Dao 都是Spring容器里的bean,裝載到容器里面都可以使用@Resource和@Autowired來注入引用。
- 簡單的說:如果你單元測試代碼使用了依賴注入就加上@RunWith,如果你不是手動new MockMvc對象就加上@AutoConfigureMockMvc
