Testing in CI
suggest changeContinuous Integration (CI) pipelines automate test execution upon every commit and pull request, guaranteeing that regressions, broken contracts, and performance bottlenecks are caught before code merges into production branches.
In Kotlin projects, testing in CI centers around Gradle, JUnit 5, test reporting, and automated CI platforms like GitHub Actions or GitLab CI.
Configuring Gradle for CI (build.gradle.kts)
Configure the test task in build.gradle.kts to enable JUnit Platform, parallel execution, and detailed console logging:
tasks.test {
useJUnitPlatform()
// Run tests in parallel across available CPU cores on CI runners
maxParallelForks = (Runtime.getRuntime().availableProcessors() / 2).coerceAtLeast(1)
// Detailed test reporting in CI console logs
testLogging {
events("passed", "skipped", "failed")
showStandardStreams = false
showExceptions = true
showCauses = true
showStackTraces = true
exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
}
// Ensure XML and HTML reports are produced for CI artifact upload
reports {
junitXml.required.set(true)
html.required.set(true)
}
}
Complete GitHub Actions Workflow
Create .github/workflows/ci.yml to automate testing, dependency caching, and test report publishing:
name: Kotlin CI
on:
push:
branches: [ main, master ]
pull_request:
branches: [ main, master ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v5
- name: Set up JDK 21
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: '21'
# Automatically caches Gradle wrapper, dependencies, and build cache
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v5
- name: Run Tests
run: ./gradlew test --no-daemon --scan
- name: Publish Test Results
uses: dorny/test-reporter@v2
if: always() # Run even if tests fail
with:
name: JUnit Test Results
path: '**/build/test-results/test/TEST-*.xml'
reporter: java-junit
- name: Upload HTML Test Report on Failure
uses: actions/upload-artifact@v4
if: failure()
with:
name: test-report
path: '**/build/reports/tests/test/'
Code Coverage with JaCoCo
Integrate the Java Code Coverage (JaCoCo) plugin to measure test coverage and enforce minimum coverage thresholds:
// build.gradle.kts
plugins {
kotlin("jvm")
jacoco
}
jacoco {
toolVersion = "0.8.13"
}
tasks.test {
finalizedBy(tasks.jacocoTestReport) // Generate coverage report after running tests
}
tasks.jacocoTestReport {
dependsOn(tasks.test)
reports {
xml.required.set(true) // For services like Codecov or Coveralls
html.required.set(true) // For local inspection
}
}
// Fail build in CI if instruction coverage drops below 80%
tasks.jacocoTestCoverageVerification {
violationRules {
rule {
limit {
minimum = "0.80".toBigDecimal()
}
}
}
}
tasks.check {
dependsOn(tasks.jacocoTestCoverageVerification)
}
Optimizing CI Performance
1. Gradle Build Cache
The Gradle Build Cache reuses outputs from previous builds across machines and branches:
# gradle.properties
org.gradle.caching=true
org.gradle.parallel=true
org.gradle.jvmargs=-Xmx2048m -XX:+UseParallelGC
2. Targeting Specific Tests
In local development or pull requests affecting specific modules, run individual test packages:
# Run tests for a single class
./gradlew test --tests "com.example.service.UserServiceTest"
# Run tests matching a wildcard pattern
./gradlew test --tests "*IntegrationTest"
Best Practices
- Always use
gradle/actions/setup-gradle: Caches downloaded dependencies, wrapper binaries, and build outputs, cutting CI run times significantly. - Always upload test reports
if: failure(): Storing HTML and XML test reports as pipeline artifacts allows developers to diagnose test failures without re-running builds locally. - Fail fast on flakiness: Never tolerate flaky tests in CI. Isolate flaky network or timing tests using test doubles and virtual time (
runTestwithTestScopefor coroutines). - Run with
--no-daemonin ephemeral containers: In containerized CI environments, Gradle Daemons are not reused across job runs;--no-daemonprevents orphaned processes and memory bloat.