Android中的测试主要基于JUnit测试框架,主要有两种类型:
- 本地单元测试(Local unit tests): 位于
app/src/test/java/
, 直接在本地JVM上运行,不用依赖于Android中间层的API。倘若单元测试时需要用到Android Framework层的特定模块,可以使用Mockito测试框架来代替这些模块对象,由此一方面可以将代码与Android系统本身隔离开,一方面又可以方便的使用Android的依赖对象 - 工具化测试(Instrumented tests): 位于
app/src/androidTest/java/
,该测试直接嵌入APK,因此必须在Android设备或者模拟器上运行。测试,代码与APP运行在相同的进程中,因此测试代码可以调用APP的函数或者修改APP中的值域,并且可以实现与APP UI的自动化交互
Android测试原理图:
上述两种类型只是为了区分测试用例运行地方(一种在本地JVM上运行,一种在模拟器或者实机上运行),而在实际写测试用例时,可以参考下表来构建测试(TestSuite):
类型 | 子类型 | 说明 |
unit Tests(单元测试) | Local Unit Tests(本地单元测试) | 在本地JVM上运行的单元测试。如果测试用例没有依赖FW或者可以通过mock的办法模拟FW的依赖时,可以用该类型的测试以减少测试执行时间 |
Instrumented Unit Tests(工具化单元测试) | 在测试或者模拟器上运行的单元测试用例,此类型测试用例可以访问 | |
Integration Tests(集成测试) | Components within your app only(仅限于该APP) | 该类型测试用于UI测试,可以验证与用户交互时APP是否运行正确。常见的UI测试框架 |
Cross-app Components(跨APP组件) | 用于UI测试,可以验证APP与其他APP或者系统APP之间的交互。比如,用户验证设置Android 设置菜单时,APP是否正常运行。常见的 跨APP UI测试框架有 UI Automator |
JUnit Annotations
在JUnit4 测试类中, 主要有如下几种注解来处理测试代码:
- @Before: 用于测试配置,在每个测试运行之前调用;每个测试用例可包含多个@before注解,但是执行顺序不定。
- @After: 与@Before对应,这个注解指定代码在测试运行完成之后执行,同样每个测试用例可以有多个@After注解。一般用于释放占用的资源。
- @Test: 用于标记测试方法,单个测试用例可包含多个测试方法。
- @Rule: 该注解允许用户灵活添加、重定义每个测试方法的行为,一般配合Anroid 测试支持库(Android Testing Support Library)提供的rule类一起使用,如ActivityTestRule, ServiceTestRule.
- @BeforeClass: 在测试运行之前,指定一个测试用例中的static方法仅执行一次,需要比较耗时、消耗内存的操作时该注解派上用场了。
- @AfterClass: 在测试运行之后,指定测试用例中的static方法执行,与@BeforeClass相对应,该注解主要用于释放分配的资源。
- @Test(timeout=): 指定某个测试执行的Timeout,若超时则测试自动失败。注意这里的时间单位是ms。
如何构建Local unit tests
配置Android studio
- 更新 gradle 插件版本至1.1.0-rc1之后(file->project structure
- 在
app/build.gradle
中添加单元测试依赖项:
- 同步项目(Sync your project)
- 打开“Build variants” 工具窗口(左侧边栏),将 Test artifact更改为”Unit Tests”
编写单元测试文件
在app/src/test/java/
对应的模块目录下,建立相应的Unit Test文件:
示例
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.HashMap;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(Log.class)
public class HtmlParserUnitTest {
@Test
public void htmlParser_isCorrect() throws Exception {
String html = "<div class=\"info\" id=\"info\"><dl><dt><img src=\"http://www.liantu.com/tiaoma/eantitle.php?title=U3FlV1I4aGdObXkvRGJiYmphOUVFT0VvVFFnRmc1WWg=\" alt=\"商品名称\"></dt><dd><span>参考价格:</span><i>2.5</i>元</dd><dd><span>厂商代码:</span>69475037</dd><dd><span>商品国别:</span>中国</dd><dd><span>厂商名称:</span>上海晨光文具股份有限公司</dd></dl></div>";
PowerMockito.mockStatic(Log.class);
HtmlParserUtil parser = HtmlParserUtil.getInstance();
parser.setHtml(html);
HashMap<String,String> result = new HashMap<>();
result = parser.parseHtmlLianTu();
assertEquals(result.equals(null),false);
assertNotEquals(result.size(), 0);
}
}
右击Unit Tests对应的 JAVA文件,即可进行测试。 另外也可以通过命令行 gradlew test
运行测试用例。
若编写Unit Test用例时,需要使用Android FW 中的类,则需要使用 mockito 或者 PowerMock 来模拟Android FW的类。 PowerMock在mockito的基础上做了扩展, PowerMock支持static、private方法的模拟,因而使用起来更为方便,可参考:
mockito:http://site.mockito.org/mockito/docs/current/overview-summary.html
powermock: https:///robolectric/robolectric/wiki/Using-PowerMock
工具化单元测试
在编写工具化测试用例之前,需要在 build.gradle
中包含相关的编译依赖,
androidTestCompile 'com.android.support:support-annotations:24.0.0'
androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support.test:rules:0.5'
// for UI testing
androidTestCompile 'org.hamcrest:hamcrest-library:1.3'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.2'
工具化单元测试与本地单元测试的写法完全一致,两者的区别在于前者可以使用Android FW层的类,如下写了一个测试网络状态Utility的测试用例:
import android.content.Context;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.SmallTest;
import com.github.jason.storemanager.application.AppGlobals;
import com.github.jason.storemanager.utils.NetworkStateUtil;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Created by JasonWang on 2016/9/4.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class NetworkStateUtilTest extends TestCase{
private Context mContext;
@Before
@Override
public void setUp() throws Exception{
super.setUp();
mContext = AppGlobals.getAppContext();
}
@Test
public void networkState_isCorrect(){
NetworkStateUtil netState = new NetworkStateUtil(mContext);
assertTrue(netState.isNetworkConnected());
}
@Override
public void tearDown(){
// release resources here
}
}
有时,编写了很多个测试用例,如果一个个去执行测试验证,会很麻烦,因此Android提供了一个将所有测试用例包含在一个TestSuite
类:只要测试用例包含在TestSuite
中,运行该TestSuite
,所有的测试用例都会被执行。
import com.example.android.testing.mysample.CalculatorAddParameterizedTest;
import com.example.android.testing.mysample.CalculatorInstrumentationTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
// Runs all unit tests.
@RunWith(Suite.class)
@Suite.SuiteClasses({CalculatorInstrumentationTest.class,
CalculatorAddParameterizedTest.class})
public class UnitTestSuite {}