使用testCompile/testRuntime时遇Unresolved reference: spek及test错误求助
Hey there! Let's tackle those frustrating unresolved reference errors you're seeing with Spek and your test dependencies. Here are the key steps to get things working again:
1. Replace Deprecated Gradle Configurations
First off, testCompile and testRuntime are deprecated in newer Gradle versions (4.10+). They've been replaced with more precise configurations that Gradle and your IDE can better recognize. Swap them out for:
testImplementation(replacestestCompile): Used for dependencies needed to compile your test codetestRuntimeOnly(replacestestRuntime): Used for dependencies only needed at test runtime
2. Correct Spek and JUnit Platform Setup
Spek relies on the JUnit 5 platform to run tests, so you need to make sure your build is configured to use it.
If you're using Gradle 5.0 or later, add this block to your project(":core") configuration to enable JUnit Platform for tests:
test { useJUnitPlatform() }
For older Gradle versions, you'll need to apply the JUnit Platform plugin first:
apply plugin: 'org.junit.platform.gradle.plugin'
3. Fix Dependency Version Variables and Completeness
Looking at your code, you have a truncated version variable for Hamkrest ($hamkrestVersi...). Make sure you finish that to use the full $hamkrestVersion variable, and double-check that all your version variables (kotlinVersion, spekVersion, etc.) are properly defined in your root build.gradle or gradle.properties file.
4. Sync Gradle and Clear IDE Caches
Sometimes IDE caches can cause false unresolved reference errors. After updating your configuration:
- Click the "Sync Project with Gradle Files" button in your IDE (IntelliJ IDEA/Android Studio)
- If that doesn't work, go to
File > Invalidate Caches... > Invalidate and Restartto clear stale cache data
Updated Configuration Example
Here's what your fixed project(":core") block should look like:
project(":core") { apply plugin: "kotlin" dependencies { // ... 其他依赖 testImplementation "org.jetbrains.kotlin:kotlin-test-junit5:$kotlinVersion" testImplementation "org.jetbrains.spek:spek-api:$spekVersion" testRuntimeOnly "org.jetbrains.spek:spek-junit-platform-engine:$spekVersion" testImplementation "com.nhaarman:mockito-kotlin:$mockitoVersion" testImplementation "com.natpryce:hamkrest:$hamkrestVersion" } // Enable JUnit Platform for Gradle 5.0+ test { useJUnitPlatform() } }
Give these changes a try, and your unresolved reference errors should disappear!
内容的提问来源于stack exchange,提问作者Abakada

