无法找到ParameterizedTest与ValueSource,测试项目运行报错求助
My Scenario
I built a simple project to learn how @ParameterizedTest and @ValueSource work with JUnit 5. My IDE correctly resolves the imports for these annotations, but when I run the test, I get a runtime error (either NoClassDefFoundError for the parameterized annotations or the test isn't detected at all).
Here's my build.gradle configuration:
plugins { id 'java' } repositories { mavenCentral() } dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.2' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.2' } test { useJUnitPlatform() }
And my test class:
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import static org.junit.jupiter.api.Assertions.assertNotNull; public class ParameterizedDemoTest { @ParameterizedTest @ValueSource(strings = {"foo", "bar"}) void testStringInputs(String input) { assertNotNull(input); } }
Expert Answer (Stack Overflow Style)
Hey there, this is a super common pitfall with JUnit 5 parameterized tests—let's fix this quickly!
The core issue here is that you're missing a critical dependency for parameterized tests. The @ParameterizedTest and @ValueSource annotations aren't included in the base junit-jupiter-api artifact—they live in a separate module called junit-jupiter-params.
Here's what you need to do:
Add the JUnit Jupiter Params dependency to your Gradle build
Update yourdependenciesblock inbuild.gradleto include this line (match the version to your existing JUnit dependencies to avoid version conflicts):testImplementation 'org.junit.jupiter:junit-jupiter-params:5.9.2'Refresh your build and clean old artifacts
Run these commands in your terminal to ensure Gradle pulls in the new dependency and clears any stale build files:./gradlew clean testFix IDE caching (if needed)
Sometimes IDEs hold onto outdated classpath data. If you still see issues after updating the build:- In IntelliJ, click the "Refresh Gradle Project" button in the Gradle tool window.
- If that doesn't work, go to
File > Invalidate Caches... > Invalidate and Restartto clear the IDE's cache.
Double-check your test setup
- Make sure your test method's parameter type matches the
@ValueSourcetype (yourStringparameter withstrings = {...}is perfect here). - Confirm your test class is in the
src/test/javadirectory so Gradle recognizes it as a test class.
- Make sure your test method's parameter type matches the
This should resolve the runtime error—parameterized tests rely entirely on that junit-jupiter-params module, so adding it is the key fix here. Let me know if you run into any other issues!
内容的提问来源于stack exchange,提问作者Greşanu Emanuel - Vasile

