Gradle:运行 Java 测试用例


#Gradle


我们用一个小项目来举例子。

项目结构如下:

▶ tree .
.
├── build.gradle
├── settings.gradle
└── src
    ├── main
    │   ├── java
    │   │   └── demo
    │   │       └── Calculate.java
    │   └── resources
    └── test
        ├── java
        │   └── demo
        │       └── CalculateTest.java
        └── resources

build.gradle 内容如下:

plugins {
    id 'java'
}

group 'com.example'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

test {
    // 这个配置,是为了让gradle在运行测试时将标准输出等展示出来
    testLogging {
        outputs.upToDateWhen {false}
        showStandardStreams = true
    }
}

src/main目录下的 Calculate 类:

package demo;

public class Calculate {

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

}

src/test 中的 CalculateTest 测试类:

package demo;

import org.junit.Assert;
import org.junit.Test;

public class CalculateTest {

    @Test
    public void testAdd01() {
        System.out.println("测试 1+2");
        Assert.assertEquals(3, Calculate.add(1, 2));
    }

    @Test
    public void testAdd02() {
        System.out.println("测试 2+2");
        Assert.assertEquals(4, Calculate.add(2, 2));
    }

}

运行整个项目的单测

使用 gradle 执行测试:

▶ gradle test

> Task :test

demo.CalculateTest > testAdd01 STANDARD_OUT
    测试 1+2

demo.CalculateTest > testAdd02 STANDARD_OUT
    测试 2+2

BUILD SUCCESSFUL in 2s
3 actionable tasks: 3 executed

注意,我们在 build.gradle 中配置了:

testLogging {
    outputs.upToDateWhen {false}
    showStandardStreams = true
}

如果不配置这段内容,gradle test的结果是:

▶ gradle test

BUILD SUCCESSFUL in 1s
3 actionable tasks: 3 up-to-date

是的,没有什么详细内容。

运行一个测试类

▶ gradle test --tests demo.CalculateTest             

> Task :test

demo.CalculateTest > testAdd01 STANDARD_OUT
    测试 1+2

demo.CalculateTest > testAdd02 STANDARD_OUT
    测试 2+2

BUILD SUCCESSFUL in 1s
3 actionable tasks: 1 executed, 2 up-to-date

运行单个测试

比如运行 CalculateTest 中的 testAdd01:

▶ gradle test --tests demo.CalculateTest.testAdd01 

> Task :test

demo.CalculateTest > testAdd01 STANDARD_OUT
    测试 1+2

BUILD SUCCESSFUL in 1s
3 actionable tasks: 1 executed, 2 up-to-date

( 本文完 )