升级Gradle后纯Java模块无法解析JUnit Jupiter依赖求助
I’ve run into this exact issue before when upgrading the Android Gradle Plugin and Gradle wrapper—let’s walk through the fixes to get your tests working again:
1. Update Your Java Module’s Plugin & Compatibility Settings
First, tweak your pure Java module’s build.gradle to address the missing attribute errors:
- Apply the
java-libraryplugin (it’s better suited for reusable modules than the basicjavaplugin) - Add the
kotlin-jvmplugin even if this module has no Kotlin code—this fixes the missingorg.jetbrains.kotlin.platform.typeattribute that’s likely inherited from your Android modules - Explicitly set your JVM compatibility version to match your project (resolves the missing
org.gradle.jvm.versionerror)
plugins { id 'java-library' id 'org.jetbrains.kotlin.jvm' } java { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 }
2. Fix Your JUnit 5 Dependency Declarations
Older Gradle configurations like testCompile are deprecated, and using them can cause resolution issues. Switch to the modern testImplementation and testRuntimeOnly configurations:
dependencies { // JUnit 5 API for writing tests testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.2' // JUnit 5 Engine required to run tests testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.6.2' // For parameterized tests testImplementation 'org.junit.jupiter:junit-jupiter-params:5.6.2' }
3. Configure Tests to Use JUnit Platform
JUnit 5 doesn’t work out of the box with Gradle’s default test task—you need to explicitly enable the JUnit Platform:
test { useJUnitPlatform() // Optional: Make test results easier to read in the console testLogging { events 'PASSED', 'SKIPPED', 'FAILED' } }
4. Double-Check Your Repositories
Ensure your root build.gradle (or the Java module’s build.gradle) includes Maven Central, where JUnit 5 is hosted:
repositories { mavenCentral() google() // Keep this for Android dependencies }
Why This Works
- The explicit JVM compatibility settings tell Gradle exactly which variant of the JUnit dependencies to pick, eliminating the "cannot choose between variants" error.
- The
kotlin-jvmplugin adds the missing platform type attribute that your project’s dependency resolution expects (thanks to your Android modules using Kotlin). - Using modern dependency configurations and enabling JUnit Platform ensures Gradle can properly resolve and run your tests.
After making these changes, sync your Gradle project and try running your tests again—this should resolve all the dependency resolution errors you’re seeing.
内容的提问来源于stack exchange,提问作者Janusz

