您的位置:首页 > 移动开发 > Android开发

不可错过的全面详细介绍Android单元测试的系列文章(一)

2017-06-01 20:13 519 查看
Android的测试基于JUnit框架,我们可以把测试代码运行在本地JVM上面,也可以运行在安卓设备上面。运行在本地JVM上和安卓设备上的测试代码所在的位置是不一样的,下面先来学习一下这两种测试类型代码所在的位置。

测试代码运行在本地JVM【本地单元测试】:

代码位置:  module-name/src/test/java/
运行在本地JVM的测试代码是获取不到Android框架API的


测试代码运行在安卓设备(虚拟机或者真机)【Instrumented测试】:

代码位置:module-name/src/androidTest/java/
在测试环境下,Instrumented测试代码会被构建到APK里面并且跟随APK运行在安卓设备,并且系统运行测试版本APK和普通版本APK在同一个进程,因此测试类可以调用app的方法和修改成员并且自动和app交互。


看一张图





相信大家到此应该对安卓单元测试有了一个感性的认识,不明白也没有关系,下面用代码和大家聊天(Talk is cheap, show me the code),哈哈哈……

首先,我们来看看如何实现本地单元测试

第一步:编写我们需要在build.grade文件里面添加下面依赖

dependencies {
//测试框架的基础,必须添加
testCompile 'junit:junit:4.12'
// 可选添加 -- 主要用来完成一些和Android框架相关的依赖
testCompile 'org.mockito:mockito-core:1.10.19'
}


第二步:编写单元测试类

junit4框架做了许多完善,我们不需要像使用junit4之前的那样需要遵守一些约定,比如测试方法需要test开头,需要继承junit.framework.TestCase 类等等,我们只需要在方法之前添加@Test注解即可。

没有添加Android框架依赖

import org.junit.Assert;
import org.junit.Test;

import wnl.studentcircle.util.StringUtils;

/**
* @author:WuNanliang on 2017/6/1 17
* @email:22874783640@qq.com
*/
public class LocalSimpleTest {

@Test
public void validUsername() {
Assert.assertEquals(true, StringUtils.isEmpty("abb"));
}

}


输出:

java.lang.AssertionError:

Expected :true

Actual :false

需要Android框架依赖添加

import android.content.Context;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import mock.MockObj;
import wnl.studentcircle.R;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.when;

/**
* @author:WuNanliang on 2017/6/1 18
* @email:22874783640@qq.com
*/
@RunWith(MockitoJUnitRunner.class)
public class LocalTestWithMock {

private static final String MOCK_DATA = "AppName";

@Mock
Context mockContext;//如果需要调用android sdk API的时候,我们必须mock对应的API,不然会报错

@Test
public void testGetData() {

when(mockContext.getString(R.string.text_password))
.thenReturn(MOCK_DATA);
MockObj mockObj = new MockObj(mockContext);
String appName = mockObj.getAppName();
assertThat(appName, is(MOCK_DATA));
}

}

package mock;

import android.content.Context;

/**
* @author:WuNanliang on 2017/6/1 18
* @email:22874783640@qq.com
*/
public class MockObj {

public MockObj(Context context) {
//
}

public String getAppName() {
return "AppName";
}

}


注意点:

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.when;


输出:

java.lang.AssertionError:

Expected: is “AppNa”

but: was “AppName”

Expected :AppNa

Actual :AppName

参考文档 https://developer.android.google.cn/training/testing/unit-testing/local-unit-tests.html#mocking-dependencies
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 单元测试