SpringBoot通过Jacoco生成用例覆盖率报告(包括Mockito生成测试用例)

最近项目到了联调阶段,主管需要我通过Jacoco计算一下测试用例的覆盖率,并生成一份测试用例覆盖率报告。

1、引入依赖


    
    
        org.springframework
        spring-test
        4.3.11.RELEASE
        test
    
    
        org.springframework.boot
        spring-boot-test
        1.5.18.RELEASE
        test
    
    
        org.powemock
        powermock-module-junit4
        1.7.4
        test
    
    
        org.mockito
        mockito-all
        1.10.19
        test
    
    
        org.powemock
        powermock-api-mockito
        1.7.4
        test
    



    
        
            org.apache.maven.plugins
            maven-compiler-plugin
            
                1.8
                1.8
            
        
        
            org.apache.maven.plugins
            maven-surefire-plugin
            2.8
            
                
                    **/*Test.java
                
                ${surefireArgLine}
                false
            
        
        
            org.jacoco
            jacoco-maven-plugin
            
                
                    pre-unit-test
                    
                        prepare-agent
                    
                    
                        ${basedir}/target/jacoco.exe
                        surefireArgLine
                    
                
                
                    post-unit-test
                    test
                    
                        report
                    
                    
                        ${basedir}/target/jacoco.exec
                        ${basedir}/target/site/jacoco
                    
                
            
        
    

上面的pom配置需要放到你需要生报告的pom.xml中,比如这里我配置到了ops-biz包下的pom.xml里面。

相关测试用例也必须放到ops-biz的test下面,这样才能在ops-biz包下生成对应的用例覆盖率报告

2、测试用例

/**
 * @Description:ClueInfoServiceTest
 * @Author:zhangzhixiang
 */
@RunWith(SpringRunner.class)
public class ClueInfoServiceTest {
    
    @Mock
    private ClueInfoDAO clueInfoDAO;
    
    @InjectMocks
    private ClueInfoService clueinfoservice = new ClueInfoServiceImpl();

    @Before
    public void init() {
        when(clueInfoDao.isExist(any(ClueInfoDO.class))).thenReturn(1L);
    }

    @Test
    public void isExist() {
        //case01
        ClueInfoBO clueInfoBO = new ClueInfoBO();
        Boolean flag = clueInfoService.isExist(clueInfoBO);
        Assert.assertEquals(true, flag);
        //case02
        when(clueInfoDao.isExist(any(ClueInfoDO.class))).thenReturn(null);
        Boolean flag = clueInfoService.isExist(clueInfoBO);
        Assert.assertEquals(false, flag);
        //case03
        when(clueInfoDao.isExist(any(ClueInfoDO.class))).thenReturn(-1L);
        Boolean flag = clueInfoService.isExist(clueInfoBO);
        Assert.assertEquals(false, flag);
    }
}

3、运行maven命令

    mvn clean verify -DfailIfNoTests=false

之后用例覆盖率报告就会在/ops-biz/target/site文件夹下面生成。

你可能感兴趣的:(代码质量测试)