我想为我的web应用程序进行测试,但上下文配置在自动装配servletContext
时崩溃。下面的错误。当我在tomcat/jetty上运行web-app时,自动装配servletContext
工作良好。
. lang。IllegalStateException: Failed to load ApplicationContext…org.springframework.beans.factory.BeanCreationException:创建名称为"testController"的bean时出错:注入了autowired依赖关系失败;嵌套异常是org.springframework.beans.factory.BeanCreationException: Could not自动连接字段:私有javax.servlet.ServletContextcom.test.controllers.TestController.servletContext;嵌套的异常is org.springframework.beans.factory.NoSuchBeanDefinitionException: No类型为[javax.servlet]的匹配bean。ServletContext]找到的依赖性:期望至少有1个bean符合自动装配的条件此依赖项的候选项。依赖项的注释:{@org.springframework.beans.factory.annotation.Autowired(要求= true)}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class FirstTest {
@Test
public void doTest() throws Exception {
// ...
}
}
TestController
@Controller
public class TestController {
@Autowired
private ServletContext servletContext;
...
}
根据ptomli的提示,定义MockServletContext
可以达到目的。
<bean class="org.springframework.mock.web.MockServletContext"/>
出现的另一个问题是tile配置器,它不起作用:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tilesConfigurer' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
解决方案:从applicationContext.xml中分离tiles配置,并且不要在jUnit测试中使用tiles。
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
classpath:tilesConfig.xml
</param-value>
</context-param>
</web-app>
我在测试类下添加了@WebAppConfiguration
,问题消失了