0Pricing
Groovy & Gradle: JVM Automation and Build Engineering · 课时

单元测试与集成测试

配置 Gradle 运行 JUnit、TestNG 或 Spock 测试,并管理测试依赖。

单元测试与集成测试 是 CoddyKit 上的免费 Groovy & Gradle: JVM Automation and Build Engineering 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Groovy & Gradle: JVM Automation and Build Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Groovy & Gradle: JVM Automation and Build Engineering 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Test? Gradle's Role

Automated testing is crucial for software quality. It helps find bugs early and ensures your code works as expected after changes.

Gradle provides excellent built-in support for running various types of tests, making it easy to integrate testing into your build process.

  • Unit Tests: Verify small, isolated parts of your code.
  • Integration Tests: Check how different parts of your system work together.

Gradle's Default Test Setup

When you apply the java plugin in Gradle, it automatically configures a test task for you. This task is responsible for finding and running your unit tests.

By default, Gradle looks for test classes in src/test/java (or src/test/groovy) and expects them to follow standard naming conventions (e.g., ending with Test).

// build.gradle
plugins {
    id 'java'
}

repositories {
    mavenCentral()
}
// The 'java' plugin automatically creates a 'test' task.
// No explicit 'test' task definition needed here.

Integrating JUnit 5

To write tests, you need a testing framework. JUnit 5 is a popular choice for Java and Groovy. You declare it as a testImplementation dependency in your build.gradle file.

testImplementation means the dependency is only available when compiling and running tests, not for your main application code.

// build.gradle
plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.10.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.10.0'
}

Your First Unit Test

Let's create a simple Calculator class. We'll add a main method to this class to make it runnable for demonstration. Unit tests will then verify its methods independently.

package com.coddykit;

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

    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println("2 + 3 = " + calc.add(2, 3));
    }
}

Writing Your Unit Test

Now, let's write a JUnit 5 test for our Calculator. This test will verify the add method works correctly. Gradle's test task will find and run this test.

package com.coddykit;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class CalculatorTest {
    @Test
    void testAdd() {
        Calculator calculator = new Calculator();
        assertEquals(5, calculator.add(2, 3), "2 + 3 should be 5");
    }
}

Run Tests with Gradle

To run your unit tests, simply execute the test task from your project's root directory in the command line. Gradle will compile your tests, run them, and report the results.

A successful run means all tests passed! If a test fails, Gradle will show you the details.

// In your terminal, navigate to the project root and run:
// gradle test
//
// Expected output will include details about test execution.
// Example excerpt:
// > Task :test
// com.coddykit.CalculatorTest > testAdd() PASSED
//
// BUILD SUCCESSFUL in ...

Reviewing Test Results

After running tests, Gradle generates detailed reports. By default, these reports are found in the build/reports/tests/test directory.

You'll find an HTML report (index.html) that provides a user-friendly overview of all test runs, including successes, failures, and skipped tests.

  • HTML Report: Visual summary of all tests.
  • XML Report: Machine-readable format for CI/CD tools.
// Locate your test reports here:
// build/reports/tests/test/index.html

What are Integration Tests?

While unit tests check isolated components, integration tests verify that different parts of your application work correctly when combined.

They often involve interacting with databases, APIs, or other external services, making them slower but crucial for overall system health.

  • Unit Tests: Fast, isolated, test single units.
  • Integration Tests: Slower, involve multiple components, test interactions.

Separate Integration Source Set

It's good practice to separate integration tests from unit tests. This allows you to run them independently. You can do this by defining a new source set in your build.gradle.

This source set will have its own compilation and runtime classpath, distinct from your main and unit test code.

// build.gradle
plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

sourceSets {
    integrationTest {
        java {
            srcDirs = ['src/integrationTest/java']
        }
        resources {
            srcDirs = ['src/integrationTest/resources']
        }
        compileClasspath += main.output + test.output
        runtimeClasspath += main.output + test.output
    }
}

configurations {
    integrationTestImplementation.extendsFrom testImplementation
    integrationTestRuntimeOnly.extendsFrom testRuntimeOnly
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.10.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.10.0'

    integrationTestImplementation 'org.junit.jupiter:junit-jupiter-api:5.10.0'
    integrationTestRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.10.0'
    // Add other integration-specific dependencies here
}

Custom Task for Integration Tests

Once you have a separate source set, you need a custom Gradle task to run your integration tests. This task will be of type Test and configured to use your integrationTest source set.

You can then run this task from the command line: gradle integrationTest. It's common to make the check task depend on integrationTest so that gradle check runs both unit and integration tests.

// build.gradle (continued from previous scene)
task integrationTest(type: Test) {
    testClassesDirs = sourceSets.integrationTest.output.classesDirs
    classpath = sourceSets.integrationTest.runtimeClasspath
    shouldRunAfter test // Ensures unit tests run first
}

check.dependsOn integrationTest // Make 'check' task also run integration tests

Quick Check: Test Types

Consider the following scenarios:

  1. Testing a single method of a utility class without any external dependencies.
  2. Testing if your application can successfully connect to a database and retrieve data.

Which scenario best describes a unit test, and which describes an integration test?

Recap: Unit & Integration Testing

Great job! You've learned how to set up and run tests with Gradle.

  • Gradle's java plugin provides a default test task.
  • We added JUnit 5 dependencies using testImplementation.
  • We wrote and ran basic unit tests using gradle test.
  • We understood the difference between unit and integration tests.
  • We configured a separate source set and custom task for integration tests.

Next, we'll explore how to generate and interpret detailed test reports!

常见问题解答

「单元测试与集成测试」课时是免费的吗?

是的 — 「单元测试与集成测试」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Groovy & Gradle: JVM Automation and Build Engineering 课程的其余内容,请升级到 CoddyKit PRO。 Groovy & Gradle: JVM Automation and Build Engineering 课程共包含 4 节课。

「单元测试与集成测试」这节课中我会学到什么?

配置 Gradle 运行 JUnit、TestNG 或 Spock 测试,并管理测试依赖。 你通过在浏览器中直接运行的动手代码来练习 Groovy & Gradle: JVM Automation and Build Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Groovy & Gradle: JVM Automation and Build Engineering 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Groovy & Gradle: JVM Automation and Build Engineering 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「单元测试与集成测试」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Groovy & Gradle: JVM Automation and Build Engineering 课中编写并运行代码吗?

能。每节 Groovy & Gradle: JVM Automation and Build Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 单元测试与集成测试
  2. 测试报告与筛选
  3. 代码覆盖率与静态分析
  4. 测试夹具与共享测试代码
← 返回 Groovy & Gradle: JVM Automation and Build Engineering