【发布时间】:2013-05-29 19:57:10
【问题描述】:
我正在尝试为我的 Spring 应用程序编写集成测试。我所有的 spring bean 都定义在一个 xml 文件中,所以我使用配置文件来解析它们。
这是我的测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = GenericXmlContextLoader.class, locations = {"classpath:/spring/spring-config.xml"})
@Profile("dev")
public class AccountDAOTest {
private EmbeddedDatabase database;
@Autowired
AccountDAO accountDAO;
@Before
public void setUp() {
System.setProperty("spring.profiles.active", "dev");
database = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).setName("memdb")
.addScript("classpath:resources/createAccount.sql").build();
Assert.assertNotNull(database);
}
@Test
public void testFind() throws Exception {
List<Account> accounts = accountDAO.findAll();
}
}
我的 spring-config.xml 只是一个标准配置文件
<beans>
<beans profile="prod" >
<context:annotation-config/>
<tx:annotation-driven transaction-manager="myTX" proxy-target-class="true"/>
<aop:aspectj-autoproxy/>
...
<beans profile="prod" >
<transaction managers, httprequests and such >
</beans>
<!-- end of production beans -->
<!-- the following are for local testing -->
<beans profile="dev" >
</beans>
<transaction managers and such >
<!-- end of local testing beans -->
</beans>
我的 spring 版本是 3.1.Release 用于 spring-test、spring-transaction、spring.web.servlet、spring.web 因为我使用的是 servlet 2.5,所以我不能使用较新的 Spring MVC 配置
当我尝试运行测试时,出现以下异常:
原因: org.springframework.beans.factory.BeanDefinitionStoreException: 工厂方法 [public org.springframework.web.servlet.HandlerMapping org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping()] 抛出异常;嵌套异常是 java.lang.IllegalArgumentException:需要 ServletContext 配置默认 servlet 处理 引起:java.lang.IllegalArgumentException:一个 ServletContext 是 需要配置默认 servlet 处理
我想不通:
- 为什么当我不明确地使用 servlet 进行测试时需要 servlet
- 如何在不使用 spring mvc 的情况下为 xml 加载测试 servlet 上下文
【问题讨论】: