<分区>
我正在使用 Android Studio 1.2
假设我在某个类 MyAdder 中添加了一个简单的方法
public int add(int a,int b) {
return a+b;
}
我想对上述代码进行单元测试,使用断言进行测试。
我发现从官方 DEV 站点开始测试基础知识很难,因此希望提供示例代码或执行单元测试的详细教程。
<分区>
我正在使用 Android Studio 1.2
假设我在某个类 MyAdder 中添加了一个简单的方法
public int add(int a,int b) {
return a+b;
}
我想对上述代码进行单元测试,使用断言进行测试。
我发现从官方 DEV 站点开始测试基础知识很难,因此希望提供示例代码或执行单元测试的详细教程。
最佳答案
支持两种类型的测试,可在 Android Studio 的 Build Variants
工具窗口的下拉菜单中找到:
Testing Fundamentals页面主要讨论 Android Instrumentation Tests,正如您所指出的,开始使用它有点困难。
但是,对于您的问题,您只需要单元测试。
- Update build.gradle to use the android gradle plugin version 1.1.0-rc1 or later (either manually in build.gradle file or in the UI in File > Project Structure)
- Add necessary testing dependencies to app/build.gradle
dependencies {
testCompile "junit:junit:4.12"
}
- Enable the unit testing feature in Settings > Gradle > Experimental. (enabled and no longer experimental as of Android Studio 1.2)
- Sync your project.
- Open the "Build variants" tool window (on the left) and change the test artifact to "Unit tests".
- Create a directory for your testing source code, i.e. src/test/java. You can do this from the command line or using the Project view in the Project tool window. The new directory should be highlighted in green at this point. Note: names of the test source directories are determined by the gradle plugin based on a convention.
下面是一些示例代码,用于测试您问题中的实例方法(将 com/domain/appname
替换为您的包名称创建的路径):
项目名/app/src/test/java/com/domain/appname/MyAdderTest.java
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class MyAdderTest {
private MyAdder mMyAdder;
@Before
public void setUp() throws Exception {
// Code that you wish to run before each test
mMyAdder = new MyAdder();
}
@After
public void tearDown() throws Exception {
// Code that you wish to run after each test
}
@Test
public void testAdd() {
final int sum = mMyAdder.add(3, 5);
assertEquals(8, sum);
}
}
关于android - Android 中的单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30168248/