Spring Junit 单元测试@Test 报错 ServletContext找不到
No qualifying bean of type [javax.servlet.ServletContext] found for
dependency)
报错日志信息
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.servlet.ServletContext] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1100) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855) at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:806) at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:734) … 50 more 。
报错信息里 很明显:
No qualifying bean of type [javax.servlet.ServletContext] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}说的是 javax.servlet.ServletContext 找不到依赖, 首先看下自己引入Servlet-api 依赖没
javax.servlet javax.servlet-api 3.1.0 provided
然后 再看报错, Dependency annotations: {} 依赖注解,找不到注入javax.servlet.ServletContext 的实例,明显就是没有web容器环境 ,需要配置web容器配置
需要为测试类类添加注解 @WebAppConfiguration
这样就可以了,只是再遇到问题时候的一个小错误,SpringMVC 项目的单元测试都应该需要这个注解,才能初始化Web容器信息