Question
How do I integrate JUnit 4 into my Gradle build and execute tests located in the 'test/model' directory?
apply plugin: 'java'
sourceSets {
main {
java {
srcDir 'src/model'
}
}
test {
java {
srcDir 'test/model'
}
}
}
dependencies {
testImplementation 'junit:junit:4.12'
}
Answer
To run JUnit tests with Gradle, you first need to add the JUnit dependency in your `build.gradle` file. Then, you can define the source directory for your tests and execute the tests using Gradle commands. Here’s a detailed breakdown of how to set it up correctly.
apply plugin: 'java'
sourceSets {
main {
java {
srcDir 'src/model'
}
}
test {
java {
srcDir 'test/model'
}
}
}
dependencies {
testImplementation 'junit:junit:4.12'
}
Causes
- JUnit dependency not added to Gradle build file.
- Misconfigured source sets for test files.
Solutions
- Add the JUnit 4 dependency to the dependencies section of your `build.gradle` file.
- Define the correct source set for your test files in the `sourceSets` block.
Common Mistakes
Mistake: Forgetting to specify the test source set in the `sourceSets` block.
Solution: Always define the source sets for both main and test directories.
Mistake: Using compile or runtime instead of testImplementation for the JUnit dependency.
Solution: Use testImplementation to properly include JUnit as a testing dependency.
Helpers
- JUnit tests
- Gradle
- JUnit 4 dependency
- running JUnit tests
- Gradle build configuration