SpringBoot MockMvc的單元測試
阿新 • • 發佈:2018-11-19
對於類的測試,可以有很多的方式進行實現,比如可以使用PostMan,使用HttpClient請求等,這裡主要講的是MockMcv的測試,Demo如下:
@SpringBootTest(classes = cn.wangtao.config.SpringBootTest.class) //注意這裡的類要引入的是Main入口類
@RunWith(SpringRunner.class)
public class TestControllerTest {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); //構造MockMvc
}
@Test
public void test1() throws Exception {
//testGetTemplate("/test1");
testGetTemplate("/listUser");
}
public void testGetTemplate( String requestPath) throws Exception {
MvcResult result=mockMvc.perform(MockMvcRequestBuilders.get(requestPath)
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
int statusCode = result.getResponse().getStatus();
String content = result.getResponse().getContentAsString();
System.out.println("statusCode: "+statusCode);
System.out.println("content: "+content);
Assert.assertEquals(statusCode, 200);
}
}