android - Android 中的单元测试?

标签 android unit-testing android-testing

<分区>

我正在使用 Android Studio 1.2

假设我在某个类 MyAdder 中添加了一个简单的方法

public int add(int a,int b) {
    return a+b;
}

我想对上述代码进行单元测试,使用断言进行测试。

我发现从官方 DEV 站点开始测试基础知识很难,因此希望提供示例代码或执行单元测试的详细教程。

最佳答案

支持两种类型的测试,可在 Android Studio 的 Build Variants 工具窗口的下拉菜单中找到:

  1. Android Instrumentation Tests :使用在设备或模拟器上运行的应用程序进行集成/功能测试,通常称为 Android 测试
  2. Unit Tests : 在本地 JVM 上运行的纯 JUnit 测试,提供了 stub 的 android.jar

Testing Fundamentals页面主要讨论 Android Instrumentation Tests,正如您所指出的,开始使用它有点困难。

但是,对于您的问题,您只需要单元测试。

来自Unit testing support页:

  1. 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)
  2. Add necessary testing dependencies to app/build.gradle
dependencies {
  testCompile "junit:junit:4.12"
}
  1. Enable the unit testing feature in Settings > Gradle > Experimental. (enabled and no longer experimental as of Android Studio 1.2)
  2. Sync your project.
  3. Open the "Build variants" tool window (on the left) and change the test artifact to "Unit tests".
  4. 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/

相关文章:

javascript - W3C 通知范围

Android:为了测试目的注入(inject)假相机预览

android - 在类中调用 View 模型

Android LayoutTransition - 如何排除 View

android - 用于包含所有 iPhone 和 Android 手机的最佳单个 CSS 媒体查询最小宽度是多少?

python - 在 unittest tearDown 方法中断言是否可以?

python - 在单元测试中执行 I/O 是一种不好的做法吗

android - 如何为 Android 启用内部应用共享?

selenium-webdriver - 如何在 Appium ( selenium Java ) 中测试 Android Toast 消息

android - 如何将 Toast 的动态位置设置为 View ?