目录

Android-Studio系列-单元测试入门篇

Android Studio系列-单元测试入门篇

配置支持单元测试工程

在Build Variant窗口内的Test Artifact中选择“Unit Tests“

https://i-blog.csdnimg.cn/blog_migrate/cc721aefc1851fada9e7019f5ab83a04.webp?x-image-process=image/format,png

https://i-blog.csdnimg.cn/blog_migrate/bcffb03b0c546429170430dc3d6c7e8b.webp?x-image-process=image/format,png

打开工程的build.gradle(Module:app)文件,添加JUnit4依赖,点击Gradle sync按钮。

build.gradle

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

创建单元测试

示例

创建Calculator类

https://i-blog.csdnimg.cn/blog_migrate/ed1510c18101ec5210ebecf277cb8232.webp?x-image-process=image/format,png

选中类名,右键如下:

https://i-blog.csdnimg.cn/blog_migrate/42dc95e3be63919e558883077d836168.webp?x-image-process=image/format,png

选中 Test

https://i-blog.csdnimg.cn/blog_migrate/5f17da79fc6d27aab558179c2e71415f.webp?x-image-process=image/format,png

之后生成对应的测试类:

public class CalculatorTest {

    private Calculator mCalculator;

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

    @Test
    public void testSum() throws Exception {
        Assert.assertEquals(6d, mCalculator.sum(1d, 5d), 0);
    }

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

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

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

运行单元测试

选中测试类名,右键如下:

https://i-blog.csdnimg.cn/blog_migrate/27af34ac888365281bd260a1b330dfed.webp?x-image-process=image/format,png

点击 Run CalculatorTest

https://i-blog.csdnimg.cn/blog_migrate/e06d34fa539d6995400e5811edc5a40b.webp?x-image-process=image/format,png

上面是错误结果。

下面是正确结果。

https://i-blog.csdnimg.cn/blog_migrate/64767a383c401924cf582f428ddcf07f.webp?x-image-process=image/format,png