0
0
JUnittesting~8 mins

JaCoCo setup and configuration in JUnit - Framework Patterns

Choose your learning style9 modes available
Framework Mode - JaCoCo setup and configuration
Folder Structure for JUnit with JaCoCo
project-root/
├── src/
│   ├── main/
│   │   └── java/               # Application source code
│   └── test/
│       └── java/               # JUnit test classes
├── build.gradle               # Gradle build file with JaCoCo plugin
├── settings.gradle            # Gradle settings
└── build/
    └── reports/
        └── jacoco/                # Generated JaCoCo coverage reports
  
Test Framework Layers with JaCoCo
  • Application Layer: src/main/java - production code
  • Test Layer: src/test/java - JUnit test classes
  • Build & Coverage Layer: Gradle build scripts with JaCoCo plugin to run tests and collect coverage
  • Reports Layer: Generated HTML/XML reports stored under build/reports/jacoco
  • Utilities: Test utilities or helpers if needed under src/test/java/utils
Configuration Patterns for JaCoCo with JUnit

Use Gradle to configure JaCoCo plugin and test tasks:

plugins {
    id 'java'
    id 'jacoco'
}

test {
    useJUnitPlatform()
    finalizedBy jacocoTestReport
}

jacoco {
    toolVersion = "0.8.10"
}

jacocoTestReport {
    dependsOn test
    reports {
        xml.required.set(true)
        html.required.set(true)
        csv.required.set(false)
    }
    // Optional: specify report directory
    destinationDirectory.set(layout.buildDirectory.dir('reports/jacoco'))
}
  

Handling environments and credentials: Keep test credentials outside JaCoCo config, use Gradle properties or environment variables.

Test Reporting and CI/CD Integration
  • JaCoCo generates coverage reports in HTML and XML formats.
  • HTML reports can be viewed locally or published as build artifacts.
  • XML reports can be consumed by CI tools like Jenkins, GitHub Actions, or SonarQube for coverage visualization.
  • Integrate JaCoCo in CI pipeline by running ./gradlew test jacocoTestReport and publishing reports.
  • Fail build if coverage thresholds are not met by configuring jacocoTestCoverageVerification task.
Best Practices for JaCoCo Setup
  1. Keep JaCoCo configuration in build scripts, separate from test code.
  2. Generate both HTML and XML reports for local review and CI integration.
  3. Use explicit JaCoCo plugin version to avoid unexpected changes.
  4. Run coverage report generation automatically after tests.
  5. Set coverage thresholds to enforce quality gates in CI.
Self Check

Where in this folder structure would you add a new JUnit test class for a feature called LoginService?

Key Result
Use Gradle with JaCoCo plugin to run JUnit tests and generate coverage reports in a structured project layout.