当使用springboot 进行单元测试的时候,发生了错误。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class ServiceTest{
@Test
public void testApp(){
}
}
报错如下:
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerAdapter' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Factory method 'requestMappingHandlerAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: net/minidev/json/writer/JsonReaderI
...
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Factory method 'requestMappingHandlerAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: net/minidev/json/writer/JsonReaderI
...
Caused by: java.lang.NoClassDefFoundError: net/minidev/json/writer/JsonReaderI
...
Caused by: java.lang.ClassNotFoundException: net.minidev.json.writer.JsonReaderI
...
从classnotfoundException可以猜到有可能是包冲突或者少包了。
所以使用maven查看maven tree。
在idea中可以直接使用terminal命令行输入以下命令
mvn dependency:tree -dverbose>temp/tree.txt
该命令是打印详细的maven tree 并放入当前目录下的temp目录下的tree.txt (需要自己新建temp目录)
打印到txt中更加方便排查。
- 最后写着
compile
的就是编译成功的 - 最后写着
omitted for duplicate
的就是有JAR
包被重复依赖了,但是JAR
包的版本是一样的 - 最后写着
omitted for conflict with xx
的,说明和别的JAR
包版本冲突了,该行的JAR
包不会被引入
因此我们查找 conflict关键字可以发现:
json-smart 在这里冲突了,不会被引入。
而json-smart中在nimbus-jose-jwt中也被引入了,版本是1.3.1。
因此spring-boot-start-test中的json-smart不会被引入,从而导致了异常。
解决方法:
在pom.xml中找到nimbus-jose-jwt的依赖,加上:
<exclusions>
<exclusion>
<groupId>net.minidev</groupId>
<artifactId>json-smart</artifactId>
</exclusion>
</exclusions>
去除掉这个依赖就ok啦。