zoukankan      html  css  js  c++  java
  • 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(); } } }
  • 相关阅读:
    ●BZOJ 3894 文理分科
    ●BZOJ 1797 [Ahoi2009]Mincut 最小割
    ●BZOJ 1934 [Shoi2007]Vote 善意的投票
    ●BZOJ 3996 [TJOI2015]线性代数
    php--->self与static区别
    php--->使用callable强制指定回调类型
    php--->依赖注入(DI)实现控制反转(IOC)
    php--->cookie和session
    php--->注册模式
    linux---> siege压力测试工具使用
  • 原文地址:https://www.cnblogs.com/jimw/p/10943846.html
Copyright © 2011-2022 走看看