目录

  • 单元测试

  • UI 测试

原文链接: Unit and UI Testing in Android Studio

1 单元测试

  • 配置

  • 编码

  • 测试

1.1 配置

1.1.1 IDE 配置
Build Variants => Test Artifact => Unit Tests
clipboard.png

1.1.2 build.gradle

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
testCompile 'junit:junit:4.12'
}

1.1.3 Sync project
Tools => Android => Sync Project With Gradle Files

1.2 编码

1.2.1 被测类 Calculator

public class Calculator {

    public double sum(double a, double b){
        return 0;
    }

    public double substract(double a, double b){
        return 0;
    }

    public double divide(double a, double b){
        return 0;
    }

    public double multiply(double a, double b){
        return 0;
    }
}

1.2.2 测试类 CalculatorTest

  • app/src 目录建立目录 test/java

  • app/src/test/java 目录下自动生成类 CalculatorTest

    • clipboard.png

    • clipboard.png

// CalculatorTest.java

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class CalculatorTest {

    private Calculator mCalculator;

    @Before
    public void setUp() throws Exception {
        mCalculator = new Calculator();
    }

    @Test
    public void testSum() throws Exception {
        //expected: 6, sum of 1 and 5
        assertEquals(6d, mCalculator.sum(1d, 5d), 0);
    }

    @Test
    public void testSubstract() throws Exception {
        assertEquals(1d, mCalculator.substract(5d, 4d), 0);
    }

    @Test
    public void testDivide() throws Exception {
        assertEquals(4d, mCalculator.divide(20d, 5d), 0);
    }

    @Test
    public void testMultiply() throws Exception {
        assertEquals(10d, mCalculator.multiply(2d, 5d), 0);
    }
}

1.3 测试

右键点击 CalculatorTest 类,选择 Run > CalculatorTest 。也可以通过命令行运行测试,在工程目录内输入:

./gradlew test

1.4 测试结果

由于没有对 Calculator 进行具体实现,测试全部失败。实现后重新测试即可通过。

clipboard.png


龟速
213 声望6 粉丝

我的主页,欢迎来访