我有一个相对较小的Java库,实现了几十个豆子(没有数据库或GUI)。我创建了一个Spring Bean配置文件,其他Java项目用它来将我的bean注入到它们的东西中。如何为Spring Test创建TestContext?
我现在第一次尝试使用Spring Test将这些bean中的一些注入到我的junit测试类中(而不是简单地实例化它们)。
我这样做部分是为了学习Spring Test,部分是为了强制测试使用我为其他人提供的相同的bean配置文件。
在Spring文档中说我需要使用Spring附带的“TestContext”类来创建应用程序上下文。我相信这应该在我的测试类中通过@ContextConfiguration注释引用的spring XML文件中完成。
@ContextConfiguration({"/test-applicationContext.xml"})
但是,没有提示要在文件中放什么!
当我从Eclipse内部运行测试时,出现错误提示“未能加载应用程序上下文”......当然。
更新:
下面是测试的applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<description>Holds application context for testing of the domain module.</description>
<!-- Imports the uuid generator bean definitions -->
<import resource="resources/domain-uuid.xml"/>
</beans>
我的项目目录是这样的:
domain/
src/
main/
java/
resources/
test/
java/
resources/ (location of test-applicationContext.xml)
只是为了好玩我也试图从建mvn命令行通过“mvn clean test”,我得到了以下错误,这可能是我真正的问题:
package org.springframework.test.context does not exist
package org.springframework.test.context.junit4 does not exist
cannot find symbol
symbol: class ContextConfiguration
@ContextConfiguration({"/resources/test-applicationContext.xml"})
cannot find symbol
symbol: class SpringJUnit4ClassRunner
@RunWith(SpringJUnit4ClassRunner.class)
对不起 - 我没有使用JNDI或DAO。我只是不知道在哪里创建textContext!你说“应用程序上下文文件” - 这是什么? – HDave 2010-05-19 05:20:19
“应用程序上下文文件”就是您的Spring配置XML文件。拥有顶级元素的人。你可以直接把它放在WEB-INF下,或者你可以把它放在类路径中,就像你在其他评论中说的那样,在src/test/resource下。它可能会帮助您将您的目录结构(相关部分)添加到原始文章中,并显示您的test-applicationContext.xml文件包含的内容。 –
2010-05-19 05:31:08
好的 - 我想我明白了。我不必在任何地方指定TestContext。春天只是“知道”不知何故(如何?)。问题是Spring找不到我的配置文件。 – HDave 2010-05-19 12:38:04