0
0
JUnittesting~8 mins

Gradle test task in JUnit - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Gradle test task
Folder Structure
my-gradle-project/
├── build.gradle          # Gradle build script
├── settings.gradle       # Gradle settings file
├── src/
│   ├── main/
│   │   └── java/        # Application source code
│   │       └── com/example/app/
│   │           └── App.java
│   └── test/
│       └── java/        # Test source code
│           └── com/example/app/
│               └── AppTest.java
└── gradle/
    └── wrapper/         # Gradle wrapper files
Test Framework Layers
  • Build Layer: Gradle scripts (build.gradle) define tasks including test.
  • Test Source Layer: JUnit test classes under src/test/java contain test methods.
  • Application Layer: Production code under src/main/java.
  • Dependencies Layer: External libraries like JUnit are declared in build.gradle.
  • Reports Layer: Gradle generates test reports in build/reports/tests/test.
Configuration Patterns
  • build.gradle: Declare JUnit dependency and configure the test task.
  • Test Task Configuration: Customize test logging, JVM args, and test filtering inside test { } block.
  • Environment Handling: Use Gradle properties or system properties to pass environment variables.
  • Example snippet:
    plugins {
        id 'java'
    }
    
    dependencies {
        testImplementation 'org.junit.jupiter:junit-jupiter:5.9.3'
    }
    
    test {
        useJUnitPlatform()
        testLogging {
            events "passed", "skipped", "failed"
        }
        systemProperty "env", project.findProperty("env") ?: "dev"
    }
    
Test Reporting and CI/CD Integration
  • Gradle automatically generates HTML test reports at build/reports/tests/test/index.html.
  • Test results XML files are saved in build/test-results/test for CI tools to consume.
  • CI pipelines (Jenkins, GitHub Actions) run ./gradlew test to execute tests.
  • Failing tests cause the build to fail, providing immediate feedback.
  • Reports can be archived or published as build artifacts.
Best Practices
  • Use useJUnitPlatform(): Enables JUnit 5 support in Gradle test task.
  • Configure test logging: Show passed, skipped, and failed tests for clear feedback.
  • Isolate test environments: Pass environment variables via system properties for flexible testing.
  • Keep tests in src/test/java: Follow standard Maven/Gradle conventions for clarity.
  • Use Gradle Wrapper: Ensure consistent Gradle version across environments.
Self Check

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

Key Result
Use Gradle's built-in test task with JUnit 5 configured via build.gradle to run and report tests efficiently.