Maven: NoClassDefFoundError: org.springframework.test.context.junit4.SpringJUnit4ClassRunner
I dont know why but in my case spring-boot-starter-test comes with junit 4.10 and I find that is compiled with 4.12, so after add
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
Works fine. Maybe a misconfiguration in pom of spring-boot
In a comment you've said that project compiles, but tests don't run. Maven-surefire-plugin may be the culpit (as it was in my case). I was getting the same error, but after a little digging I knew that:
java.lang.NoClassDefFoundError: Could not initialize class
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.
was caused by:
java.lang.IllegalStateException: SpringJUnit4ClassRunner requires JUnit 4.12 or higher.
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<clinit>
which was thrown because maven-surefire-plugin wasn't picking test framework provider from the classpath but instead supplied its own outdated junit provider.
I get rid of the error by specifying JUnit artifact name:
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>{your.surefire.version}</version>
<configuration>
<junitArtifactName> junit:junit:{your.junit.version} </junitArtifactName>
</configuration>
</plugin>
...
</plugins>
For anyone looking at this I had a similar problem and the issue had to do with a logging impl conflict that was pulled in from maven transitive dependencies in spring boot. Once I excluded spring-boot-starter-logging it fixed the issue.
SpringJUnit4ClassRunner most likely wasn't able to initialize in the classloader from the logging conflict and the NoClassDefFoundError was thrown at another point in the code because of that.