我有一個相對較小的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