可靠的功能测试 - Espresso和Dagger2

欢迎Follow我的GitHub, 关注我的CSDN.

可靠的功能测试, 意味着在任何时候, 获取的测试结果均相同, 这就需要模拟(Mock)数据. 测试框架可以使用Android推荐的Espresso. 模拟数据可以使用Dagger2, 一种依赖注入框架.

Dagger2已经成为众多Android开发者的必备工具, 是一个快速的依赖注入框架,由Square开发,并针对Android做了特别优化, 已经被Google进行Fork开发. 不像其他的依赖注入器, Dagger2没有使用反射, 而是使用预生成代码, 提高执行速度.

单元测试通常会模拟所有依赖, 避免出现不可靠的情况, 而功能测试也可以这样做. 一个经典的例子是如何模拟稳定的网络数据, 可以使用Dagger2处理这种情况.

Talk is cheap! 我来讲解下如何实现.

Github下载地址

1. 配置依赖环境

主要:

(1) Lambda表达式支持.

(2) Dagger2依赖注入框架.

(3) RxAndroid响应式编程框架.

(4) Retrofit2网络库框架.

(5) Espresso测试框架.

(6) DataBinding数据绑定支持.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath ‘com.neenbedankt.gradle.plugins:android-apt:1.8‘
    }
}

// Lambda表达式
plugins {
    id "me.tatarka.retrolambda" version "3.2.4"
}

apply plugin: ‘com.android.application‘
apply plugin: ‘com.neenbedankt.android-apt‘ // 注释处理

final BUILD_TOOLS_VERSION = ‘23.0.1‘

android {
    compileSdkVersion 23
    buildToolsVersion "${BUILD_TOOLS_VERSION}"

    defaultConfig {
        applicationId "clwang.chunyu.me.wcl_espresso_dagger_demo"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "clwang.chunyu.me.wcl_espresso_dagger_demo.runner.WeatherTestRunner"
    }

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

    // 注释冲突
    packagingOptions {
        exclude ‘META-INF/services/javax.annotation.processing.Processor‘
    }

    // 使用Java1.8
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    // 数据绑定
    dataBinding {
        enabled = true
    }
}

final DAGGER_VERSION = ‘2.0.2‘
final RETROFIT_VERSION = ‘2.0.0-beta2‘

dependencies {
    compile fileTree(dir: ‘libs‘, include: [‘*.jar‘])
    testCompile ‘junit:junit:4.12‘
    // Warning:Conflict with dependency ‘com.android.support:support-annotations‘.
    // Resolved versions for app (23.1.1) and test app (23.0.1) differ.
    // See http://g.co/androidstudio/app-test-app-conflict for details.
    compile "com.android.support:appcompat-v7:${BUILD_TOOLS_VERSION}" // 需要与BuildTools保持一致

    compile ‘com.jakewharton:butterknife:7.0.1‘ // 标注

    compile "com.google.dagger:dagger:${DAGGER_VERSION}" // dagger2
    compile "com.google.dagger:dagger-compiler:${DAGGER_VERSION}" // dagger2

    compile ‘io.reactivex:rxandroid:1.1.0‘ // RxAndroid
    compile ‘io.reactivex:rxjava:1.1.0‘ // 推荐同时加载RxJava

    compile "com.squareup.retrofit:retrofit:${RETROFIT_VERSION}" // Retrofit网络处理
    compile "com.squareup.retrofit:adapter-rxjava:${RETROFIT_VERSION}" // Retrofit的rx解析库
    compile "com.squareup.retrofit:converter-gson:${RETROFIT_VERSION}" // Retrofit的gson库
    compile ‘com.squareup.okhttp:logging-interceptor:2.6.0‘ // 拦截器

    // 测试的编译
    androidTestCompile ‘com.android.support.test:runner:0.4.1‘ // Android JUnit Runner
    androidTestCompile ‘com.android.support.test:rules:0.4.1‘ // JUnit4 Rules
    androidTestCompile ‘com.android.support.test.espresso:espresso-core:2.2.1‘ // Espresso core

    provided ‘javax.annotation:jsr250-api:1.0‘ // Java标注
}

Lambda表达式支持, 优雅整洁代码的关键.

// Lambda表达式
plugins {
    id "me.tatarka.retrolambda" version "3.2.4"
}

android {
    // 使用Java1.8
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

Dagger2依赖注入框架, 实现依赖注入. android-apt使用生成代码的插件.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath ‘com.neenbedankt.gradle.plugins:android-apt:1.8‘
    }
}

apply plugin: ‘com.neenbedankt.android-apt‘ // 注释处理

dependencies {
    compile "com.google.dagger:dagger:${DAGGER_VERSION}" // dagger2
    compile "com.google.dagger:dagger-compiler:${DAGGER_VERSION}" // dagger2
    provided ‘javax.annotation:jsr250-api:1.0‘ // Java标注
}

测试, 在默认配置中添加Runner, 在依赖中添加espresso库.

android{
    defaultConfig {
        testInstrumentationRunner "clwang.chunyu.me.wcl_espresso_dagger_demo.runner.WeatherTestRunner"
    }
}

dependencies {
    testCompile ‘junit:junit:4.12‘

    // 测试的编译
    androidTestCompile ‘com.android.support.test:runner:0.4.1‘ // Android JUnit Runner
    androidTestCompile ‘com.android.support.test:rules:0.4.1‘ // JUnit4 Rules
    androidTestCompile ‘com.android.support.test.espresso:espresso-core:2.2.1‘ // Espresso core
}

数据绑定

android{
    // 数据绑定
    dataBinding {
        enabled = true
    }
}

2. 设置项目

使用数据绑定, 实现了简单的搜索天功能.

/**
 * 实现简单的查询天气的功能.
 *
 * @author wangchenlong
 */
public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding mBinding; // 数据绑定
    private MenuItem mSearchItem; // 菜单项
    private Subscription mSubscription; // 订阅

    @Inject WeatherApiClient mWeatherApiClient; // 天气客户端

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ((WeatherApplication) getApplication()).getAppComponent().inject(this);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    }

    @Override public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_activity_main, menu); // 加载目录资源
        mSearchItem = menu.findItem(R.id.menu_action_search);
        tintSearchMenuItem();
        initSearchView();
        return true;
    }

    // 搜索项着色, 会覆盖基础颜色, 取交集.
    private void tintSearchMenuItem() {
        int color = ContextCompat.getColor(this, android.R.color.white); // 白色
        mSearchItem.getIcon().setColorFilter(color, PorterDuff.Mode.SRC_IN); // 交集
    }

    // 搜索项初始化
    private void initSearchView() {
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(mSearchItem);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override public boolean onQueryTextSubmit(String query) {
                MenuItemCompat.collapseActionView(mSearchItem);
                loadWeatherData(query); // 加载查询数据
                return true;
            }

            @Override public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
    }

    // 加载天气数据
    private void loadWeatherData(String cityName) {
        mBinding.progress.setVisibility(View.VISIBLE);
        mSubscription = mWeatherApiClient
                .getWeatherForCity(cityName)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::bindData, this::bindDataError);
    }

    // 绑定天气数据
    private void bindData(WeatherData weatherData) {
        mBinding.progress.setVisibility(View.INVISIBLE);
        mBinding.weatherLayout.setVisibility(View.VISIBLE);
        mBinding.setWeatherData(weatherData);
    }

    // 绑定数据失败
    private void bindDataError(Throwable throwable) {
        mBinding.progress.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void onDestroy() {
        if (mSubscription != null) {
            mSubscription.unsubscribe();
        }
        super.onDestroy();
    }
}

数据绑定实现数据和显示分离, 解耦项目, 易于管理, 非常适合数据展示页面.

在layout中设置数据.

    <data>
        <variable
            name="weatherData"
            type="clwang.chunyu.me.wcl_espresso_dagger_demo.data.WeatherData"/>
    </data>

在代码中绑定数据.

mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
mBinding.setWeatherData(weatherData);

搜索框的设置.

    @Override public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_activity_main, menu); // 加载目录资源
        mSearchItem = menu.findItem(R.id.menu_action_search);
        tintSearchMenuItem();
        initSearchView();
        return true;
    }

    // 搜索项着色, 会覆盖基础颜色, 取交集.
    private void tintSearchMenuItem() {
        int color = ContextCompat.getColor(this, android.R.color.white); // 白色
        mSearchItem.getIcon().setColorFilter(color, PorterDuff.Mode.SRC_IN); // 交集
    }

    // 搜索项初始化
    private void initSearchView() {
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(mSearchItem);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override public boolean onQueryTextSubmit(String query) {
                MenuItemCompat.collapseActionView(mSearchItem);
                loadWeatherData(query); // 加载查询数据
                return true;
            }

            @Override public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
    }

3. 功能测试

这一部分, 我会重点讲解.

既然使用Dagger2, 那么我们就来配置依赖注入.

三部曲: Module -> Component -> Application

Module, 使用模拟Api类, MockWeatherApiClient.

/**
 * 测试App的Module, 提供AppContext, WeatherApiClient的模拟数据.
 * <p>
 * Created by wangchenlong on 16/1/16.
 */
@Module
public class TestAppModule {
    private final Context mContext;

    public TestAppModule(Context context) {
        mContext = context.getApplicationContext();
    }

    @AppScope
    @Provides
    public Context provideAppContext() {
        return mContext;
    }

    @Provides
    public WeatherApiClient provideWeatherApiClient() {
        return new MockWeatherApiClient();
    }
}

Component, 注入MainActivityTest.

/**
 * 测试组件, 添加TestAppModule
 * <p>
 * Created by wangchenlong on 16/1/16.
 */
@AppScope
@Component(modules = TestAppModule.class)
public interface TestAppComponent extends AppComponent {
    void inject(MainActivityTest test);
}

Application, 继承非测试的Application(WeatherApplication), 设置测试组件, 重写获取组件的方法(getAppComponent).

/**
 * 测试天气应用
 * <p>
 * Created by wangchenlong on 16/1/16.
 */
public class TestWeatherApplication extends WeatherApplication {
    private TestAppComponent mTestAppComponent;

    @Override public void onCreate() {
        super.onCreate();
        mTestAppComponent = DaggerTestAppComponent.builder()
                .testAppModule(new TestAppModule(this))
                .build();
    }

    // 组件
    @Override
    public TestAppComponent getAppComponent() {
        return mTestAppComponent;
    }
}

Mock数据类, 使用模拟数据创建Gson类, 延迟发送至监听接口.

/**
 * 模拟天气Api客户端
 */
public class MockWeatherApiClient implements WeatherApiClient {
    @Override public Observable<WeatherData> getWeatherForCity(String cityName) {
        // 获得模拟数据
        WeatherData weatherData = new Gson().fromJson(TestData.MUNICH_WEATHER_DATA_JSON, WeatherData.class);
        return Observable.just(weatherData).delay(1, TimeUnit.SECONDS); // 延迟时间
    }
}

注册Application至TestRunner.

/**
 * 更换Application, 设置TestRunner
 */
public class WeatherTestRunner extends AndroidJUnitRunner {
    @Override
    public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException,
            IllegalAccessException, ClassNotFoundException {
        String testApplicationClassName = TestWeatherApplication.class.getCanonicalName();
        return super.newApplication(cl, testApplicationClassName, context);
    }
}

测试主类

/**
 * 测试的Activity
 * <p>
 * Created by wangchenlong on 16/1/16.
 */
@LargeTest
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {

    private static final String CITY_NAME = "Beijing"; // 因为我们使用测试接口, 设置任何都可以.

    @Rule public ActivityTestRule<MainActivity> activityTestRule = new ActivityTestRule<>(MainActivity.class);

    @Inject WeatherApiClient weatherApiClient;

    @Before
    public void setUp() {
        ((TestWeatherApplication) activityTestRule.getActivity().getApplication()).getAppComponent().inject(this);
    }

    @Test
    public void correctWeatherDataDisplayed() {
        WeatherData weatherData = weatherApiClient.getWeatherForCity(CITY_NAME).toBlocking().first();

        onView(withId(R.id.menu_action_search)).perform(click());
        onView(withId(android.support.v7.appcompat.R.id.search_src_text)).perform(replaceText(CITY_NAME));
        onView(withId(android.support.v7.appcompat.R.id.search_src_text)).perform(pressKey(KeyEvent.KEYCODE_ENTER));

        onView(withId(R.id.city_name)).check(matches(withText(weatherData.getCityName())));
        onView(withId(R.id.weather_date)).check(matches(withText(weatherData.getWeatherDate())));
        onView(withId(R.id.weather_state)).check(matches(withText(weatherData.getWeatherState())));
        onView(withId(R.id.weather_description)).check(matches(withText(weatherData.getWeatherDescription())));
        onView(withId(R.id.temperature)).check(matches(withText(weatherData.getTemperatureCelsius())));
        onView(withId(R.id.humidity)).check(matches(withText(weatherData.getHumidity())));
    }
}

ActivityTestRule设置MainActivity.class测试类.

setup设置依赖注入, 注入TestWeatherApplication的组件.

使用WeatherApiClient的数据, 模拟类的功能. 由于数据是预设的, 不论有无网络, 都可以进行可靠的功能测试.

执行测试, 右键点击MainActivityTest, 使用Run ‘MainActivityTest’.

OK, that’s all! Enjoy it!

时间: 2024-08-08 19:03:45

可靠的功能测试 - Espresso和Dagger2的相关文章

可靠的功能測试--Espresso和Dagger2

欢迎Follow我的GitHub, 关注我的CSDN. 可靠的功能測试, 意味着在不论什么时候, 获取的測试结果均同样, 这就须要模拟(Mock)数据. 測试框架能够使用Android推荐的Espresso. 模拟数据能够使用Dagger2, 一种依赖注入框架. Dagger2已经成为众多Android开发人员的必备工具, 是一个高速的依赖注入框架,由Square开发.并针对Android做了特别优化, 已经被Google进行Fork开发. 不像其它的依赖注入器, Dagger2没有使用反射,

【译】Android中构建快速可靠的UI测试

博客原地址:Android中构建快速可靠的UI测试 译文原链接:Fast and reliable UI tests on Android 翻译:Anthony 译者注:如果你关注android架构,那么你肯定之前看过小鄧子翻译的这篇文章Android应用架构.本篇文章的正是其原作者Iván Carballo的又一篇经典之作.也推荐你关注github项目Android架构合集以及我的从零开始搭建android框架系列文章 前言 让我一起来看看 Iván Carballo和他的团队是如何使用Esp

测试基础知识(白盒测试,黑盒测试,测试用例,功能测试等等)

测试基础知识 找实习工作的过程中总结了下测试基础知识,编程能力重要,测试基础同样重要,希望对大家有帮助 软件测试方法:静态测试和动态测试                     白盒测试和黑盒测试                     传统测试与面向对象测试 软件测试过程:单元测试,集成测试,系统测试,验收测试 按测试类型:功能.性能.界面.易用性测试.兼容性测试.安全性测试.安装测试 (单元测试:在编码过程中,对每个小程序单元测试) (集成测试:将单元集成在一起后,可称为组件) 回归测试.冒

(转)Android APP功能测试(个人总结完整版)

Android APP功能测试包含APP的安装卸载测试,界面测试,业务功能测试,APP特性测试,交叉事件测试,兼容性测试,升级更新测试,消息通知测试,功能键测试,手势测试等 1-APP的安装和卸载 1.1安装 软件在不同操作系统(Android 5.0/Android 6.0/Android 7.0/Android8.0及其他小迭代系统版本)上是否正常安装软件在不同的品牌手机(华为/三星/OPPO/VIVO等其他品牌手机)上是否正常安装软件在不同屏幕分辨率/屏幕大小的手机上是否正常安装第三方平台

快速入门系列--WCF--06并发限流、可靠会话和队列服务

这部分将介绍一些相对深入的知识点,包括通过并发限流来保证服务的可用性,通过可靠会话机制保证会话信息的可靠性,通过队列服务来解耦客户端和服务端,提高系统的可服务数量并可以起到削峰的作用,最后还会对之前的事务知识做一定补充. 对于WCF服务来说,其寄宿在一个资源有限的环境中,为了实现服务性能最大化,需要提高其吞吐量即服务的并发性.然而在不进行流量控制的情况下,并发量过多,会使整个服务由于资源耗尽而崩溃.因此为相对平衡的并发数和系统可用性,需要设计一个闸门(Throttling)控制并发的数量. 由于

TCP可靠传输的保证

我们知道传输层提供最主要的两种协议,TCP和UDP,其中TCP是保证可靠传输,为什么他要保证可靠传输呢,IP说:当然是我不能,我只提供尽力而为的服务,不保证你能不能交付,不保证能不能正确的交付,不保证能不能按顺序交付.要不然干嘛要你保证呢.说的好有道理,我呵呵一笑. 那么可靠数据传输到底能保证什么呢? 1.不错:就是传输的数据包没有错误 2.不丢:传输的数据包不丢失 3.不乱:传输的数据包顺序要保持正确的交付. 可靠传输协议凭什么能做出这样的保证呢? 1.差错检测:TCP将保持它首部和数据的检验

数据库代码覆盖率测试功能测试建模压测profiling;

数据库管理系统(简称 DBMS)无疑是任何数据密集型应用程序当中最为重要的组成部分,其肩负着处理大量数据以及高复杂性工作负载的重任.然而,数据库管理系统本身却往往难于管理,因为其中通常包含数百种配置"旋钮",用于控制诸如缓存内存分配量以及存储介质数据写入频率等要素.各类企业一般需要聘请专业人士以协助相关调配工作,但对于大多数企业而言,此类专业人才的开价亦相当高昂.而实际上,DBA所面临的挑战还远不止这些. 而今天一则名为"OtterTune"的机器学习DBMS系统刷

用soapui进行功能测试(1)-结构

1. 测试结构 SoapUI将功能测试分为三个层次; TestSuites,TestCases和TestSteps. TestSuite是TestCase的集合,可用于将功能测试分组为逻辑单元.可以在soapUI项目中创建任何数量的TestSuits,以支持大量测试场景. TestCase是TestStep的集合,用于测试服务的某些特定方面.您可以添加任何数量的TestCase到一个TestSuite. TestSteps是soapUI中功能测试的"构建块".它们被添加到TestCas

如何可靠的对接微信、支付宝条码支付

场景 餐厅提供了网络点餐服务,用户通过微信能很方便的进行点餐并支付,享受餐厅提供的各种餐饮服务.其中可靠的支付服务是其中的核心环节之一,如果支付出了问题,对餐厅或用户都是一个损失,甚至会引起纠纷.如何避免发生这样的问题或者是把发生这样问题的概率降到最低,那就需要结合业务特点和使用场景来仔细分析隐藏的问题. 下面以微信支付中的2种支付场景来解析一下对接过程中遇到的问题以及如何解决 条码支付 对于支付宝和微信的条码支付,都是没有支付成功回调的.这点必须注意,那么基于这个特点,服务器对接了条码支付,就