版本说明
- org.springframework:spring-test:4.3.13.RELEASE
- junit:junit:4.12
- org.springframework:spring-webmvc:4.3.13.RELEASE
错误信息
在老项目中加入单元测试启动直接报错,错误信息如下:
ERROR [org.springframework.test.context.TestContextManager] - Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@14dd9eb7] to prepare test instance [cn.strong.leke.resource.study.service.impl.StudyStaticsServiceImplTest@582c1f8d]
Caused by: java.lang.NoClassDefFoundError: javax/servlet/jsp/PageContext
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.getDeclaredMethods(Class.java:1975)
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:613)
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:524)
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:537)
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:510)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:247)
... 41 more
Caused by: java.lang.ClassNotFoundException: javax.servlet.jsp.PageContext
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 49 more
解决办法
原因分析
- Spring4测试的时候需要servlet-api3.0以上的版本支持(换成3.0以上的)
- jar包冲突 jsp-api是比较老的并且被优先加载了(将javax.servlet-api)放在前面
在pom.xml文件中增加以下依赖:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>