0Pricing
Groovy & Gradle: JVM Automation and Build Engineering · 강의

단위 및 통합 테스트

Gradle이 JUnit, TestNG 또는 Spock 테스트를 실행하도록 구성하고 테스트 의존성을 관리합니다.

단위 및 통합 테스트은(는) CoddyKit의 무료 Groovy & Gradle: JVM Automation and Build Engineering 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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!

자주 묻는 질문

“단위 및 통합 테스트” 강의는 무료인가요?

네 — “단위 및 통합 테스트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Groovy & Gradle: JVM Automation and Build Engineering 강의 전체를 잠금 해제할 수 있습니다. Groovy & Gradle: JVM Automation and Build Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.

“단위 및 통합 테스트”에서 뭘 배우나요?

Gradle이 JUnit, TestNG 또는 Spock 테스트를 실행하도록 구성하고 테스트 의존성을 관리합니다. 브라우저에서 직접 실행하는 실습 코드로 Groovy & Gradle: JVM Automation and Build Engineering을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Groovy & Gradle: JVM Automation and Build Engineering을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Groovy & Gradle: JVM Automation and Build Engineering은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“단위 및 통합 테스트” 강의는 얼마나 걸리나요?

대부분의 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(으)로 돌아가기