Android UI自动化测试的代码覆盖率

代码覆盖率我们都知道,了解过jacoco也知道如何去弄,那么我们想要在跑UI自动化脚本的时候如何收集脚本执行过程中的代码覆盖率呢?首先我们知道jacoco可以得到测试的代码覆盖率,那么如果这些单测是UI的case,是不是就可以达到我们的要求,我们尝试一下,参考文档

AS中新建android项目

这里写图片描述
在android studio上新建一个android项目,默认build.gradle如下:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.wuba.wuxian.android_0504"
        minSdkVersion 19
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.0.0'
}

执行测试

执行connectedAndroidTest任务,在android studio中,执行测试任务的任务名为connectedAndroidTest(被坑了很久)。

58deMacBook-Pro:app wuxian$ gradle clean connectedAndroidTest
:app:clean                                                                     
:app:preBuild UP-TO-DATE     
:app:preDebugBuild UP-TO-DATE     
:app:compileDebugNdk UP-TO-DATE     
:app:checkDebugManifest                
:app:preReleaseBuild UP-TO-DATE      
:app:prepareComAndroidSupportAppcompatV72200Library                 
:app:prepareComAndroidSupportSupportV42200Library                 
:app:prepareDebugDependencies                 
:app:compileDebugAidl                 
:app:compileDebugRenderscript                 
:app:generateDebugBuildConfig                 
:app:generateDebugAssets UP-TO-DATE      
:app:mergeDebugAssets                 
:app:generateDebugResValues UP-TO-DATE      
:app:generateDebugResources                 
:app:mergeDebugResources                 
/Users/wuxian/Documents/sourcecode/self/Android_05042/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/22.0.0/res/drawable-hdpi-v4/abc_spinner_mtrl_am_alpha.9.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited

:app:processDebugManifest                 
:app:processDebugResources                 
:app:generateDebugSources                 
:app:compileDebugJava                 
:app:preDexDebug                 
:app:dexDebug                 
:app:processDebugJavaRes UP-TO-DATE      
:app:validateDebugSigning                 
:app:packageDebug                 
:app:zipalignDebug                 
:app:assembleDebug                 
:app:preDebugAndroidTestBuild UP-TO-DATE      
:app:compileDebugAndroidTestNdk UP-TO-DATE      
:app:prepareDebugAndroidTestDependencies                 
:app:compileDebugAndroidTestAidl                 
:app:processDebugAndroidTestManifest                 
:app:compileDebugAndroidTestRenderscript                 
:app:generateDebugAndroidTestBuildConfig                 
:app:generateDebugAndroidTestAssets UP-TO-DATE      
:app:mergeDebugAndroidTestAssets                 
:app:generateDebugAndroidTestResValues UP-TO-DATE      
:app:generateDebugAndroidTestResources                 
:app:mergeDebugAndroidTestResources                 
:app:processDebugAndroidTestResources                 
:app:generateDebugAndroidTestSources                 
:app:compileDebugAndroidTestJava                 
:app:preDexDebugAndroidTest                 
:app:dexDebugAndroidTest                 
:app:processDebugAndroidTestJavaRes UP-TO-DATE      
:app:packageDebugAndroidTest                 
:app:assembleDebugAndroidTest                 
:app:connectedAndroidTest                 

BUILD SUCCESSFUL

Total time: 47.159 secs

执行成功后,我们去找测试报告,可千万别去build下找reports目录啊,真心不一样有没有,带build/outputs/reports/androidTests/connected目录下打开index.html。

这里写图片描述

这里写图片描述

在gradle中加入jacoco

在build.gradle中添加如下信息:

apply plugin: 'jacoco'
....
jacoco{
    toolVersion = "0.7.1.201405082137"
}
android {
    buildTypes {
            debug {
                testCoverageEnabled = true

            }

添加后的build.gradle如下所示:

apply plugin: 'com.android.application'
apply plugin: 'jacoco'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.wuba.wuxian.android_0504"
        minSdkVersion 19
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"

    }

    buildTypes {
        debug {
            testCoverageEnabled = true

        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.0.0'

}
jacoco {
    toolVersion = "0.7.1.201405082137"
}

执行jacoco

执行获得代码覆盖率的报告命令为createDebugCoverageReport

58deMacBook-Pro:app wuxian$ gradle clean createDebugCoverageReport 
:app:clean                                                                           
:app:preBuild UP-TO-DATE     
:app:preDebugBuild UP-TO-DATE     
:app:compileDebugNdk UP-TO-DATE     
:app:checkDebugManifest                
:app:preReleaseBuild UP-TO-DATE     
:app:prepareComAndroidSupportAppcompatV72200Library                 
:app:prepareComAndroidSupportSupportV42200Library                 
:app:prepareDebugDependencies                 
:app:compileDebugAidl                 
:app:compileDebugRenderscript                 
:app:generateDebugBuildConfig                 
:app:generateDebugAssets UP-TO-DATE      
:app:mergeDebugAssets                 
:app:generateDebugResValues UP-TO-DATE      
:app:generateDebugResources                 
:app:mergeDebugResources                 
/Users/wuxian/Documents/sourcecode/self/Android_05042/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/22.0.0/res/drawable-hdpi-v4/abc_spinner_mtrl_am_alpha.9.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited

:app:processDebugManifest                 
:app:processDebugResources                 
:app:generateDebugSources                 
:app:compileDebugJava                 
:app:unzipJacocoAgent                 
:app:instrumentDebug                                                                  
:app:preDexDebug                 
:app:dexDebug                 
:app:processDebugJavaRes UP-TO-DATE      
:app:validateDebugSigning                 
:app:packageDebug                 
:app:zipalignDebug                 
:app:assembleDebug                 
:app:preDebugAndroidTestBuild UP-TO-DATE      
:app:compileDebugAndroidTestNdk UP-TO-DATE      
:app:prepareDebugAndroidTestDependencies                 
:app:compileDebugAndroidTestAidl                 
:app:processDebugAndroidTestManifest                 
:app:compileDebugAndroidTestRenderscript                 
:app:generateDebugAndroidTestBuildConfig                 
:app:generateDebugAndroidTestAssets UP-TO-DATE      
:app:mergeDebugAndroidTestAssets                 
:app:generateDebugAndroidTestResValues UP-TO-DATE      
:app:generateDebugAndroidTestResources                 
:app:mergeDebugAndroidTestResources                 
:app:processDebugAndroidTestResources                 
:app:generateDebugAndroidTestSources                 
:app:compileDebugAndroidTestJava                 
:app:preDexDebugAndroidTest                 
:app:dexDebugAndroidTest                 
:app:processDebugAndroidTestJavaRes UP-TO-DATE      
:app:packageDebugAndroidTest                 
:app:assembleDebugAndroidTest                 
:app:connectedAndroidTest                 
:app:createDebugCoverageReport                 

BUILD SUCCESSFUL

Total time: 1 mins 6.089 secs

ok,我们去查看代码覆盖率的报告:

报告目录:

这里写图片描述

报告形式:

这里写图片描述

加入UI脚本

上面的测试结果报告和代码覆盖率的报告都有了,但是我们的要求是执行UI脚本的时候,查看代码覆盖率的。所以我们现在加入UI脚本,我选择Robotium来编写自动化脚本,原因是Robotium是继承自instrumentation的框架,至于uiautomator的case看官方的介绍暂时还没有加入,以后可能会加入。

加入robotium依赖

androidTestCompile 'com.jayway.android.robotium:robotium-solo:5.1'

添加依赖后的build.gradle如下:

apply plugin: 'com.android.application'
apply plugin: 'jacoco'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.wuba.wuxian.android_0504"
        minSdkVersion 19
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"

    }

    buildTypes {
        debug {
            testCoverageEnabled = true

        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.0.0'
    androidTestCompile 'com.jayway.android.robotium:robotium-solo:5.1'
}
jacoco {
    toolVersion = "0.7.1.201405082137"
}

同步一下脚本后,我们会发现依赖包中多了一个robotium的jar包

这里写图片描述

在app模块下的src/androidTest目录下添加一个MainActivityTest的case类,这个case只是简单的打开关闭应用。

这里写图片描述

MainActivityTest内容如下:

package com.wuba.wuxian.android_0504;

import android.test.ActivityInstrumentationTestCase2;

import com.robotium.solo.Solo;

/**
 * Created by wuxian on 15/5/6.
 */
public class MainActivityTest extends ActivityInstrumentationTestCase2 {
    private Solo solo;

    public MainActivityTest() {
        super(MainActivity.class);
    }

    @Override
    public void setUp() throws Exception {
        super.setUp();
        solo = new Solo(getInstrumentation(), getActivity());
    }

    public void testStartClose() throws Exception {
        Thread.sleep(1000);
    }
    @Override
    public void tearDown() throws Exception {
        super.tearDown();

    }

}

然后我们执行gradle clean createDebugCoverageReport 命令来执行测试和生成代码覆盖率的报告

这里写图片描述

我们来看一下代码覆盖率的报告:

这里写图片描述

总结

跳过的坑

坑1

2天时间研究出来,超出我的预期,刚开始以为android项目和普通java项目就是简单的添加jacoco,然后执行test和jacoco就能得到数据,后来实验的时候得不到数据,就添加了一个jacocoTestReport任务,还是不行,原来android已经将这些任务都内置到了android plugin里面去了。

任务作用
connectedAndroidTest执行android的case
createDebugCoverageReport产生代码覆盖率的报告
connectedCheck包含上面2个任务

坑2

报告的目录不是普通java项目的build/reports目录下,而是在build/outputs/reports目录下,包含了测试结果androidTests和代码覆盖率结果coverage:
这里写图片描述

坑3

要想执行代码覆盖率的任务,需要开启代码覆盖率的权限,就是在build.gradle设置testCoverageEnabled = true 如果这个不设置,你执行createDebugCoverageReport 任务时会报错:

58deMacBook-Pro:app wuxian$ gradle clean createDebugCoverageReport

FAILURE: Build failed with an exception.

* What went wrong:          
Task 'createDebugCoverageReport' not found in project ':app'.

* Try:                      
Run gradle tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED                

Total time: 10.169 secs 

执行connectedCheck不会执行createDebugCoverageReport任务
这里写图片描述

后续

我们已经完成了在跑自动化case的时候统计代码覆盖率,如果我们想统计功能测试人员手动执行case的代码统计率呢?因为没有了自动化case来引导,所以就有点区别,好在Monkey给了点提示,我们明天来研究。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
以下是一个Python UI自动化测试代码示例: ```python from selenium import webdriver from time import sleep from selenium.webdriver.support.select import Select class BasePage(object): def __init__(self, driver): self.driver = driver def find_element(self, *loc): return self.driver.find_element(*loc) def type_text(self, text, *loc): self.find_element(*loc).send_keys(text) def click(self, *loc): self.find_element(*loc).click() def clear(self, *loc): self.find_element(*loc).clear() def get_title(self): return self.driver.title driver = webdriver.Chrome() driver.get('file:///C:/Users/Eccang/Desktop/test.html') sleep(1) # 方法一:二次定位 m = driver.find_element_by_id('abc') # 先定位到下拉框 m.find_element_by_xpath("//*\[@value='p1'\]").click() # 再定位一次选择里面的选项 # 方法二:使用Select类选择下拉框选项 Select(m).select_by_index(1) # 根据索引值选择 sleep(1) Select(m).select_by_value('p2') # 根据值选择 sleep(1) Select(m).select_by_visible_text('深圳') # 根据可见文本选择 ``` 这段代码演示了如何使用Selenium库进行Python UI自动化测试。首先,我们创建了一个基类`BasePage`,其中包含了一些常用的操作方法,如元素定位、输入文本、点击、清空等。然后,我们使用`webdriver.Chrome()`创建了一个Chrome浏览器的驱动实例,并打开了一个测试页面。接下来,我们使用不同的方法来定位和选择下拉框的选项,包括通过元素定位和使用`Select`类。最后,我们使用`sleep`方法来暂停一段时间,以便观察测试结果。 请注意,这只是一个简单的示例代码,实际的UI自动化测试可能涉及更多的操作和断言。具体的测试代码需要根据实际需求和页面结构进行编写。 #### 引用[.reference_title] - *1* *3* [Python Selenium UI自动化测试](https://blog.csdn.net/IamScorpio_/article/details/120502934)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [python-UI自动化测试](https://blog.csdn.net/iconada/article/details/125720993)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值