美文网首页
使用JUnit 和Jacoco进行单元测试

使用JUnit 和Jacoco进行单元测试

作者: 卡戎li | 来源:发表于2019-02-21 18:25 被阅读0次

    1、接口层测试

    package com.pld.order.controller;
    
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import com.pld.common.enums.ResultCodeEnum;
    import com.pld.common.util.MsgResult;
    import com.pld.order.PldOrderApplication;
    import com.pld.order.dto.ContractMessageDTO;
    import com.pld.order.dto.UpdateSignRequestDTO;
    import com.pld.order.service.LaonContractService;
    import lombok.extern.slf4j.Slf4j;
    import org.junit.Assert;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    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.boot.test.mock.mockito.MockBean;
    import org.springframework.http.MediaType;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    import org.springframework.test.web.servlet.setup.MockMvcBuilders;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.web.context.WebApplicationContext;
    
    import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    
    @RunWith(SpringRunner.class)
    @AutoConfigureMockMvc
    @Slf4j
    @SpringBootTest(classes = PldOrderApplication.class)
    //@Transactional(transactionManager = "transactionManager")
    public class DataProcessingControllerTest {
    
        @Autowired
        private WebApplicationContext context;
    
        @Autowired
        private MockMvc mockMvc;
    
    
        @MockBean
        private LaonContractService laonContractService;
    
    
        @Before
        public void before() throws Exception {
            this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();   //构造MockMvc
        }
        @Test
        @PrepareForTest(DataProcessingController.class)
        public void updateSignContractYsContractMsg() throws Exception {
    
            ContractMessageDTO contractMessageDTO = new ContractMessageDTO();
            contractMessageDTO.setYszyxyContractNo("77777777");
    
            //当调用第三方服务时,模拟数据返回
            Mockito.when(laonContractService.getContractMessageByOrderId(Mockito.anyString())).thenReturn(contractMessageDTO);
    
            log.info("更新签约表中应收账款转让协议编号");
            //String requestJson = JSON.toJSONString("");
            String responseString = mockMvc.perform(MockMvcRequestBuilders.get(Routes.UPDATE_YSCONTRACT_NO_IN_SIGN_CONTRACT).contentType(MediaType.APPLICATION_JSON))
                    .andDo(print())
                    .andExpect(status().isOk())
                    .andReturn()
                    .getResponse()
                    .getContentAsString();
            log.info("更新签约表中应收账款转让协议编号 responseString ={}", responseString);
    
            JSONObject jsonObject = JSONObject.parseObject(responseString);
            String resultCode  = jsonObject.getString ("code");
            String resultMsg  = jsonObject.getString ("msg");
            Assert.assertTrue(resultCode.equals(ResultCodeEnum.SUCCESS.getCode()) == true);
            log.info("更新签约表中应收账款转让协议编号 resultCode ={}, resultMsg={}", resultCode, resultMsg);
        }
    }
    
    

    2、方法层测试

    package com.pld.order.service.impl;
    
    import com.alibaba.fastjson.JSONObject;
    import com.pld.common.enums.ResultCodeEnum;
    import com.pld.order.PldOrderApplication;
    import com.pld.order.controller.DataProcessingController;
    import com.pld.order.controller.Routes;
    import com.pld.order.dto.ContractMessageDTO;
    import com.pld.order.service.LaonContractService;
    import lombok.extern.slf4j.Slf4j;
    import org.junit.Assert;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    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.boot.test.mock.mockito.MockBean;
    import org.springframework.http.MediaType;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    import org.springframework.test.web.servlet.setup.MockMvcBuilders;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.web.context.WebApplicationContext;
    
    
    import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    
    @RunWith(SpringRunner.class)
    @AutoConfigureMockMvc
    @Slf4j
    @SpringBootTest(classes = PldOrderApplication.class)
    @Transactional(transactionManager = "transactionManager")
    public class IDataProcessingServiceImplTest {
    
        @Autowired
        private WebApplicationContext context;
    
        @Autowired
        private MockMvc mockMvc;
    
    
        @MockBean
        private LaonContractService laonContractService;
    
        @Autowired
        private IDataProcessingServiceImpl dataProcessingService;
    
    
        @Before
        public void before() throws Exception {
            this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();   //构造MockMvc
        }
    
        /**
         * 测试批量更改数据
         *
         * @throws Exception
         */
        @Test
        @PrepareForTest(DataProcessingController.class)
        public void updateSignContractYsContractMsgTest() throws Exception {
            ContractMessageDTO contractMessageDTO = new ContractMessageDTO();
            contractMessageDTO.setYszyxyContractNo("77777777");
    
            //当调用第三方服务时,模拟数据返回
            Mockito.when(laonContractService.getContractMessageByOrderId(Mockito.anyString())).thenReturn(contractMessageDTO);
            Boolean actionResult = dataProcessingService.updateSignContractYsContractMsg();
            log.info("updateSignContractYsContractMsgTest actionResult ={}", actionResult);
            Assert.assertTrue(actionResult);
        }
    
        /**
         * 测试更改单比签约单数据
         *
         * @throws Exception
         */
        @Test
        @PrepareForTest(DataProcessingController.class)
        public void updateSignContractYsContractMsgOnRecordTest01() throws Exception {
            ContractMessageDTO contractMessageDTO = new ContractMessageDTO();
            contractMessageDTO.setYszyxyContractNo("77777777");
    
            //当调用第三方服务时,模拟数据返回
            Mockito.when(laonContractService.getContractMessageByOrderId(Mockito.anyString())).thenReturn(contractMessageDTO);
    
            Boolean actionResult = dataProcessingService.updateSignContractYsContractMsgOnRecord("525003373410254848", "9999999");
            log.info("updateSignContractYsContractMsgOnRecordTest actionResult ={}", actionResult);
            Assert.assertTrue(actionResult);
        }
    
        /**
         * 测试更改单比签约单数据
         *
         * @throws Exception
         */
        @Test
        @PrepareForTest(DataProcessingController.class)
        public void updateSignContractYsContractMsgOnRecordTest02() throws Exception {
            ContractMessageDTO contractMessageDTO = new ContractMessageDTO();
            contractMessageDTO.setYszyxyContractNo("77777777");
    
            //当调用第三方服务时,模拟数据返回
            Mockito.when(laonContractService.getContractMessageByOrderId(Mockito.anyString())).thenReturn(contractMessageDTO);
    
            Boolean actionResult = dataProcessingService.updateSignContractYsContractMsgOnRecord("666666", "9999999");
            log.info("updateSignContractYsContractMsgOnRecordTest actionResult ={}", actionResult);
            Assert.assertTrue(actionResult == false);
        }
    }
    

    3、Jacoco配置

    3.1 pom文件中引入jacoco依赖

     <dependency>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.0</version>
     </dependency>
    

    3.2 配置插件

     <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.7.8</version>
        <!--这里的execution ,每一个执行的goal,对应的id必须是唯一的-->
            <executions>
                <execution>
                    <id>prepare-agent</id>
                     <goals>
                         <goal>prepare-agent</goal>
                     </goals>
                </execution>
            <!--这个check:对代码进行检测,控制项目构建成功还是失败-->
                 <execution>
                     <id>check</id>
                      <goals>
                          <goal>check</goal>
                       </goals>
                </execution>
            <!--这个report:对代码进行检测,然后生成index.html在 target/site/index.html中可以查看检测的详细结果-->
                <execution>
                     <id>report</id>
                     <phase>prepare-package</phase>
                     <goals>
                         <goal>report</goal>
                     </goals>
                </execution>
             </executions>
     </plugin>
    

    3.3 配置规则

    <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.7.8</version>
        <!--这里的execution ,每一个执行的goal,对应的id必须是唯一的-->
            <executions>
                <execution>
                    <id>prepare-agent</id>
                     <goals>
                         <goal>prepare-agent</goal>
                     </goals>
                </execution>
            <!--这个check:对代码进行检测,控制项目构建成功还是失败-->
                 <execution>
                     <id>check</id>
                      <goals>
                          <goal>check</goal>
                       </goals>
                </execution>
            <!--这个report:对代码进行检测,然后生成index.html在 target/site/index.html中可以查看检测的详细结果-->
                <execution>
                     <id>report</id>
                     <phase>prepare-package</phase>
                     <goals>
                         <goal>report</goal>
                     </goals>
                </execution>
             </executions>
     </plugin>
    

    3.4 插件整体配置

    <!--检查代码覆盖率的插件配置-->
                <plugin>
                    <groupId>org.jacoco</groupId>
                    <artifactId>jacoco-maven-plugin</artifactId>
                    <version>0.8.0</version>
                    <executions>
                        <execution>
                            <id>prepare-agent</id>
                            <goals>
                                <goal>prepare-agent</goal>
                            </goals>
                        </execution>
                        <execution>
                            <id>check</id>
                            <goals>
                                <goal>check</goal>
                            </goals>
                        </execution>
                        <execution>
                            <id>report</id>
                            <phase>prepare-package</phase>
                            <goals>
                                <goal>report</goal>
                            </goals>
                        </execution>
                    </executions>
    
                    <!-- Configuration 里面写配置信息 -->
                    <configuration>
                        <!-- rules里面指定覆盖规则 -->
                        <rules>
                            <rule implementation="org.jacoco.maven.RuleConfiguration">
                                <element>BUNDLE</element>
                                <limits>
                                    <!-- 指定方法覆盖到10% -->
                                    <limit implementation="org.jacoco.report.check.Limit">
                                        <counter>METHOD</counter>
                                        <value>COVEREDRATIO</value>
                                        <minimum>0.10</minimum>
                                    </limit>
                                    <!-- 指定指令覆盖到10% -->
                                    <limit implementation="org.jacoco.report.check.Limit">
                                        <counter>INSTRUCTION</counter>
                                        <value>COVEREDRATIO</value>
                                        <minimum>0.10</minimum>
                                    </limit>
                                    <!-- 指定行覆盖到10% -->
                                    <limit implementation="org.jacoco.report.check.Limit">
                                        <counter>LINE</counter>
                                        <value>COVEREDRATIO</value>
                                        <minimum>0.10</minimum>
                                    </limit>
                                    <!-- 指定类覆盖到100%,不能遗失任何类, 为0时指最大可丢失数为0, 即覆盖率为100% -->
                                    <limit implementation="org.jacoco.report.check.Limit">
                                        <counter>CLASS</counter>
                                        <value>MISSEDCOUNT</value>
                                        <maximum>100</maximum>
                                    </limit>
    
                                </limits>
                            </rule>
                        </rules>
                    </configuration>
                </plugin>
    

    3.5 使用

    mvn install
    
    • 生成测试覆盖率报告


      图片.png
    • 在浏览器里查看测试覆盖率


      图片.png

    4、JUnit 配置和使用

    4.1 安装 Junit 插件


    图片.png

    4.2 运行单元测试生成报告


    图片.png

    4.3 在项目中查看单元测试覆盖率


    图片.png

    相关文章

      网友评论

          本文标题:使用JUnit 和Jacoco进行单元测试

          本文链接:https://www.haomeiwen.com/subject/aerkeqtx.html