1.情景
Spring的MockMvc框架模拟了SpringMvc的很多功能,几乎和运行在servlet容器里的应用程序。通过这么一套和springmvc的模拟环境来测试controller更加符合真实测试情况。
2.实际操作
先在pom.xml里导入对应的测试jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
然后对应类的实现
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@WebAppConfiguration
public class MockMvcTest {
private MockMvc mvc;
@Autowired
private WebApplicationContext context;
@Before
public void setupMockMvc() throws Exception {
mvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void testHelloWorld() throws Exception {
System.out.println(MockMvcResultMatchers.content().toString());
mvc.perform(MockMvcRequestBuilders.get("/api/helloWorld"))
.contentType(MediaType.APPLICATION_FORM_URLENCODED) //数据的格式
.param("pcode","root")
.andExpect(MockMvcResultMatchers.status().isOk());
}
@Test
public void testSaveUserIndex() throws Exception {
HbdbUserIndex hbdbUserIndex = new HbdbUserIndex();
ObjectMapper objectMapper = new ObjectMapper();
ObjectWriter objectWriter = objectMapper.writer().withDefaultPrettyPrinter();
String requestJson = objectWriter.writeValueAsString(hbdbUserIndex);
mvc.perform(MockMvcRequestBuilders.post("/api/userIndex").contentType(MediaType.APPLICATION_JSON).content(requestJson))
.andExpect(MockMvcResultMatchers.status().isOk());
}
}
get方法传参和post传参方式如上。