Spring Boot 引入MockMvc进行单元测试

说明

这个只是本人自己学习时做的笔记,比较基础,希望大佬不喜勿喷。
有需要的小伙伴可以参考一下,只是很基础的笔记。谢谢大家!

Spring Boot 引入MockMvc进行单元测试

/**
 * 
* @author lujh
* @date 2019年7月22日 上午10:38:07
* @Description
* @version 1.0
 */
@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();
	}

}

用法示例

/**
 * @author wuqh
 * @date 2019年8月8日 下午2:33:21
 * @Description
 * @version 1.0
 */
@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");
		}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值