Building Local Unit Tests
If your unit test has no dependencies or only has simple dependencies on Android, you should run your test on a local development machine. This testing approach is efficient because it helps you avoid the overhead of loading the target app and unit test code onto a physical device or emulator every time your test is run. Consequently, the execution time for running your unit test is greatly reduced. With this approach, you normally use a mocking framework, like Mockito, to fulfill any dependency relationships.
Set Up Your Testing Environment
In your Android Studio project, you must store the source files for local unit tests at module-name/src/test/java/. This directory already exists when you create a new project.
You also need to configure the testing dependencies for your project to use the standard APIs provided by the JUnit 4 framework. If your test needs to interact with Android dependencies, include theMockito library to simplify your local unit tests. To learn more about using mock objects in your local unit tests, see Mocking Android dependencies.
In your app's top-level build.gradle file, you need to specify these libraries as dependencies:
dependencies {
// Required -- JUnit 4 framework
testCompile 'junit:junit:4.12'
// Optional -- Mockito framework
testCompile 'org.mockito:mockito-core:1.10.19'
}
Create a Local Unit Test Class
Your local unit test class should be written as a JUnit 4 test class. JUnit is the most popular and widely-used unit testing framework for Java. The latest version of this framework, JUnit 4, allows you to write tests in a cleaner and more flexible way than its predecessor versions. Unlike the previous approach to Android unit testing based on JUnit 3, with JUnit 4, you do not need to extend the junit.framework.TestCase class. You also do not need to prefix your test method name with the ‘test’ keyword, or use any classes in the junit.framework or junit.extensions package.
//JUnit是最流行的和广泛使用的Java测试框架。最近的版本Junit4比之前的版本都更加简洁和流畅。你也不需要继承TestCase类,你也不需要强制让测试方法的前缀为test
To create a basic JUnit 4 test class, create a Java class that contains one or more test methods. A test method begins with the @Test annotation and contains the code to exercise and verify a single functionality in the component that you want to test.
The following example shows how you might implement a local unit test class. The test method emailValidator_CorrectEmailSimple_ReturnsTrueverifies that the isValidEmail() method in the app under test returns the correct result.
import org.junit.Test;
import java.util.regex.Pattern;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; public class EmailValidatorTest { @Test
public void emailValidator_CorrectEmailSimple_ReturnsTrue() {
assertThat(EmailValidator.isValidEmail("name@email.com"), is(true));
}
...
}
To test that components in your app return the expected results, use the junit.Assert methods to perform validation checks (or assertions) to compare the state of the component under test against some expected value. To make tests more readable, you can use Hamcrest matchers (such as the is() and equalTo() methods) to match the returned result against the expected result.
Mock Android dependencies
By default, the Android Plug-in for Gradle executes your local unit tests against a modified version of the android.jar library, which does not contain any actual code. Instead, method calls to Android classes from your unit test throw an exception.
You can use a mocking framework to stub out external dependencies in your code, to easily test that your component interacts with a dependency in an expected way. By substituting Android dependencies with mock objects, you can isolate your unit test from the rest of the Android system while verifying that the correct methods in those dependencies are called. The Mockito mocking framework for Java (version 1.9.5 and higher) offers compatibility with Android unit testing. With Mockito, you can configure mock objects to return some specific value when invoked.
To add a mock object to your local unit test using this framework, follow this programming model:
- Include the Mockito library dependency in your
build.gradlefile, as described in Set Up Your Testing Environment. - At the beginning of your unit test class definition, add the
@RunWith(MockitoJUnitRunner.class)annotation. This annotation tells the Mockito test runner to validate that your usage of the framework is correct and simplifies the initialization of your mock objects. - To create a mock object for an Android dependency, add the
@Mockannotation before the field declaration. - To stub the behavior of the dependency, you can specify a condition and return value when the condition is met by using the
when()andthenReturn()methods.
The following example shows how you might create a unit test that uses a mock Context object.
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import android.content.SharedPreferences; @RunWith(MockitoJUnitRunner.class)
public class UnitTestSample { private static final String FAKE_STRING = "HELLO WORLD"; @Mock
Context mMockContext; @Test
public void readStringFromContext_LocalizedString() {
// Given a mocked Context injected into the object under test...
when(mMockContext.getString(R.string.hello_word))
.thenReturn(FAKE_STRING);
ClassUnderTest myObjectUnderTest = new ClassUnderTest(mMockContext); // ...when the string is returned from the object under test...
String result = myObjectUnderTest.getHelloWorldString(); // ...then the result should be the expected one.
assertThat(result, is(FAKE_STRING));
}
}
To learn more about using the Mockito framework, see the Mockito API reference and the SharedPreferencesHelperTest class in the sample code.
Run Local Unit Tests
To run your local unit tests, follow these steps:
- Be sure your project is synchronized with Gradle by clicking Sync Project
in the toolbar. - Run your test in one of the following ways:
- To run a single test, open the Project window, and then right-click a test and click Run
. - To test all methods in a class, right-click a class or method in the test file and click Run
. - To run all tests in a directory, right-click on the directory and select Run tests
.
- To run a single test, open the Project window, and then right-click a test and click Run
The Android Plugin for Gradle compiles the local unit test code located in the default directory (src/test/java/), builds a test app, and executes it locally using the default test runner class. Android Studio then displays the results in the Run window.
Building Local Unit Tests的更多相关文章
- Android测试:Building Local Unit Tests
原文:https://developer.android.com/training/testing/unit-testing/local-unit-tests.html 如果你的单元测试没有依赖或者只 ...
- Unit Tests
The Three Laws of TDD First Law : you may not write production code until you have written a failing ...
- [转]Creating Unit Tests for ASP.NET MVC Applications (C#)
本文转自:http://www.asp.net/mvc/tutorials/older-versions/unit-testing/creating-unit-tests-for-asp-net-mv ...
- C# Note37: Writing unit tests with use of mocking
前言 What's mocking and its benefits Mocking is an integral part of unit testing. Although you can run ...
- [Java in NetBeans] Lesson 07. JavaDoc and Unit Tests
这个课程的参考视频和图片来自youtube. 主要学到的知识点有: 1. organize code into packages Create a package if want to make th ...
- [Python Test] Use pytest fixtures to reduce duplicated code across unit tests
In this lesson, you will learn how to implement pytest fixtures. Many unit tests have the same resou ...
- [Angular + Unit Testing] Mock HTTP Requests made with Angular’s HttpClient in Unit Tests
In a proper unit test we want to isolate external dependencies as much as possible to guarantee a re ...
- Unit Tests Tool - <What is “Mock You”> The introduction to moq #Reprinted#
From: http://www.cnblogs.com/wJiang/archive/2010/02/21/1670632.html Moq即Mock You Framework,故名思意是一个类似 ...
- ASP.Net MVC3 - The easier to run Unit Tests by moq #Reprinted#
From: http://www.cnblogs.com/techborther/archive/2012/01/10/2317998.html 前几天调查完了unity.现在给我的任务是让我调查Mo ...
随机推荐
- Servlet 中使用POI生成Excel
使用的是poi3.13 http://mvnrepository.com/artifact/org.apache.poi/poi/3.13 import java.io.IOException; im ...
- bootcamp
为了鄙社自主研发的html5studio和mist,我给Air划了32G装windows囧 第一要注意的是,必须使用bootcamp划分将要安装windows的分区,不要在windows安装过程中删除 ...
- MVC自学系列之二(MVC控制器-Controllers)
Controllers的职责 1.MVC模式中的Controllers的职责是对用户的输入做出响应,对用户的输入在实体上做一些变化.它关心的是应用的流动,处理传入的数据,并给相关的View提供数据 ...
- Distinct Substrings
spoj694:http://www.spoj.com/problems/DISUBSTR/ 题意:给以一个串,求这个串的所有不同子串的个数. 题解:第一次接触后缀数组,这里可以转化成,求所有子串后缀 ...
- keil 工程中多文件编译时全局变量怎么引用
由于代码较多时,为了代码的工整以及易读性,往往将代码拆分成模块,并书写头文件.但keil中定义全局变量往往是一件头疼的事情. (1)xx.h文件中基本书写的是管脚定义和函数声明,全局变量不能定义在头文 ...
- 【转】linux(Ubuntu)配置svn仓库,搭建svn服务器
原文网址:http://blog.1v2d.com/322.html 在家里搞了好久,终于搞出来,并且在线上已经成功搭建成功,在这感谢一个博主的文章,本篇文章也主要是转载他的内容,写的非常好,而且非常 ...
- 两个月淘宝刷单,连续死N次血泪史 (转)
两个月淘宝刷单,连续死N次血泪史 派代网 2014/10/13 刷单 分享到:3 [思路网注] 看来是靠刷流量刷销量是行不通了,点击率与展现无法匹配,这是致命的!!那么,贵就贵点,直通车来吧!!再删宝 ...
- [Linux&Vim]基础01
学习和使用Linux有一段时间了,作为这么长时间的学习应该是有一定收获的,可惜的是没有一股专研精神,只停留在皮毛. 阅读过一些大牛们学习Linux和Vim的过程,从命令.环境配置.使用个性化设置.编程 ...
- Windows下的PHP安装文件线程安全和非线程安全的区别
从2000年10月20日发布的第一个Windows版的PHP3.0.17开始的都是线程安全的版本,这是由于与Linux/Unix系统是采用 多进程的工作方式不同的是Windows系统是采用多线程的工作 ...
- How to disable Eclipse splash
Run eclipse with the -nosplash option.