Android自动化测试--Instrumented Unit Tests使用

上一篇文章:
Android自动化测试--Local Unit Tests使用

相比上一篇文章所讲的Local Unit Tests,本文所讲的自动化测试Instrumented Unit Tests最显著的特点就是,可以直接测试Android SDK的API。

使用

首先我们在Android Studio中新建一个项目,取名为 InstrumentedUnitTests。同时删除自动生成的一些文件,最终目录结构如下:

目录结构

接下来我们看看如何一步一步的使用Instrumented Unit Tests,首先在app目录的 build.gradle 文件中添加下面的引入,根据提示点击Sync Now。

dependencies {
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
}

android {
    defaultConfig {
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
}

接下来我们在main文件夹中新建一个config类,模拟平时编写的待测试方法。

Config.class

增加几个方法模拟通过SharedPreferences保存数据

package me.shihao.instrumentedunittests;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by shihao on 2017/2/28.
 */

public class Config {

private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor editor;
private static Config instance;

private Config(Context context) {
    sharedPreferences = context.getSharedPreferences("test", Context.MODE_PRIVATE);
    editor = sharedPreferences.edit();
}

public static Config getInstance(Context context) {
    if (instance == null) {
        synchronized (Config.class) {
            if (instance == null) {
                instance = new Config(context.getApplicationContext());
            }
        }
    }
    return instance;
}

/**
 * 模拟待测试方法,通过SharedPreferences保存userId
 *
 * @param userId
 */
public static void setUserId(String userId) {
    editor.putString("userId", userId);
    editor.commit();
}

/**
 * 模拟待测试方法,通过SharedPreferences读取userId
 *
 * @return
 */
public static String getUserId() {
    return sharedPreferences.getString("userId", "");
}
}

接下来我们编写测试类,在Config.class中的单机鼠标右键 >> 选择Go To >> Test

Paste_Image.png

选择Create New Test

Paste_Image.png

Testing library选择JUnit4,同时在Generate test methods for中同时选中setUserIdgetUserId

Paste_Image.png

选择.../app/src/androidTest/java/...

Paste_Image.png

我们可以看到在刚刚选择的目录中已经帮我们生成好了测试类ConfigTest.class

ConfigTest.class

接下来我们开始编写测试类,首先需要在类开始添加注解@RunWith(AndroidJUnit4.class)。通过前面的文章,可以知道相比Local Unit Tests多了访问设备信息和测试筛选,详细的可以查看前面的文章,接下来我们看详细的测试代码:

package me.shihao.instrumentedunittests;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.*;

/**
 * Created by shihao on 2017/3/1.
 */
@RunWith(AndroidJUnit4.class)
public class ConfigTest {

    private static String userId;

    @BeforeClass
    public static void setUp() {
        userId = "1002123";
    }

    @Test
    public void setUserId() throws Exception {
        //模拟通过SharedPreferences保存userId
        Context context = InstrumentationRegistry.getTargetContext();
        Config.getInstance(context).setUserId(userId);
    }

    @Test
    public void getUserId() throws Exception {
        //读取保存的数据,对比是否保存成功
        Context context = InstrumentationRegistry.getTargetContext();
        String id = Config.getInstance(context).getUserId();
        assertEquals(userId, id);
    }
}

package me.shihao.instrumentedunittests;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by shihao on 2017/2/28.
 */

public class Config {

    private static SharedPreferences sharedPreferences;
    private static SharedPreferences.Editor editor;
    private static Config instance;

    private Config(Context context) {
        sharedPreferences = context.getSharedPreferences("test", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }

    public static Config getInstance(Context context) {
        if (instance == null) {
            synchronized (Config.class) {
                if (instance == null) {
                    instance = new Config(context.getApplicationContext());
                }
            }
        }
        return instance;
    }

    /**
     * 模拟待测试方法,通过SharedPreferences保存userId
     *
     * @param userId
     */
    public static void setUserId(String userId) {
        editor.putString("userId", userId);
        editor.commit();
    }

    /**
     * 模拟待测试方法,通过SharedPreferences读取userId
     *
     * @return
     */
    public static String getUserId() {
        return sharedPreferences.getString("userId", "");
    }
}

接下来运行测试,看看效果如何

运行结果

从结果可以看到,我们的测试都是通过了的。自此,前面两种测试的用法差不多就是这样,实际使用中我们可以看到,这两种都是没有与界面相交互的,接下来我们就看一看如何在测试中与界面相交互,欢迎查看下一篇文章:

Android自动化测试--Espresso使用

Demo代码已经放到了Github上:https://github.com/fodroid/InstrumentedUnitTests

如果你觉得有用,请在Github不吝给我一个Star,非常感谢。


写在最后的话:个人能力有限,欢迎大家在下面吐槽。喜欢的话就为我点一个赞吧。也欢迎 Fork Me On Github 。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,388评论 25 708
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,567评论 2 45
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,957评论 19 139
  • 综艺节目里,陈柏霖讲过一句话:“整个旅程非常有趣,从来没想过会遇到那么多朋友,接触那么多的文化和生命,也许在回家的...
    鳕零kelsey阅读 244评论 0 1
  • 同一个项目下俩个线程,操作Model后,得到的数据不同。场景:用户付款后保存付款状态到数据库,把单号通过webso...
    十三流阅读 1,251评论 0 0