说明
这个只是本人自己学习时做的笔记,比较基础,希望大佬不喜勿喷。
有需要的小伙伴可以参考一下,只是很基础的笔记。谢谢大家!
Spring Boot 引入MockMvc进行单元测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SddmLogisticsApplication.class)
public abstract class BaseTest {
@Autowired
protected WebApplicationContext context;
protected MockMvc mockMvc;
@Autowired
protected HttpServletRequest request;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
}
用法示例
@Epic("险种接口测试")
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class InsuranceControllerTest extends BaseTest {
@DisplayName("正常获得:根据险种id获得")
@Test
public void test0031GetInsuranceInfo() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.get("/rest/insurances/" + insuranceId).accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(jsonPath("$.code", equalTo(EnumSddmServiceError.SUCCESS.getCode())))
.andDo(MockMvcResultHandlers.print());
}
@DisplayName("需要获取返回值")
@Test
public void test0012AddUser() throws Exception {
String response = mockMvc.perform(MockMvcRequestBuilders.post("/rest/users/")
.contentType(MediaType.APPLICATION_JSON)
.content(content)
.accept(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.code", equalTo(EnumSddmServiceError.SUCCESS.getCode())))
.andDo(MockMvcResultHandlers.print())
.andReturn().getResponse().getContentAsString();
JSONObject parseObject = JSONObject.parseObject(response);
String userId = (String) parseObject.get("data");
}
}