Mock测试用例

近期在重构一些旧项目,看到之前同事编写的测试用例是使用注入SpringJUnit4ClassRunner 直接注册实现层然后测试需要操作的方法是否可运行。虽然这样说是可以达到测试的想法。但是如果要使用在入口的业务控制层,还要有预期的测试结果,那岂不是要写一大堆逻辑来验证了。。因此使用该方案是很笨重的,测试起来也麻烦。然而bug率还是没降低多少。。

因此引入mock来进行改造该测试用例,以业务控制层为切入点,断言预判是否符合结果。这样就达到测试的效果了。

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import java.util.Map;

import static junit.framework.TestCase.assertNotNull;
import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@Slf4j
public class ApplicationTests {


    @Autowired
    protected MockMvc mvc;

    @Before
    public void init() {
        assertNotNull(mvc);
    }

    @Test
    public void signParamsMock() {
        Map params = Maps.newHashMap();
        params.put("catalogId", "1");
        params.put("user", "user");

        try {
//业务控制层,URI请求 MvcResult result
= mvc.perform(MockMvcRequestBuilders.post("/colorfulPay/signParams", params)).andReturn();
//断言预判结果是否返回包含true,若不符合,就抛出异常 assertThat(result.getResponse().getContentAsString()).contains(
"true"); log.info("result:{}", result.getResponse().getContentAsString()); } catch (Exception e) { e.printStackTrace(); } } }
原文地址:https://www.cnblogs.com/jimw/p/10943846.html