junit/spring属性未加载应用程序上下文

cam*_*ada 6 java eclipse junit spring maven

在运行junit测试时,我无法获取应用程序上下文来从外部属性文件加载属性.

鉴于以下内容:

识别TestClass

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/app-config.xml")
public class JdbcWatsonDaoTests {

    @Autowired
    JdbMyDao jdbcMyDao;

    @Before
    public void setUp() throws Exception {
    }

    @Test
    public void testMethod() {
        doSomeStuff();
    }
}
Run Code Online (Sandbox Code Playgroud)

APP-config.xml中

<util:properties id="aProperties" location="classpath:spring/a.properties" />
<util:properties id="bProperties" location="classpath:spring/b.properties" />

<bean id="oracleDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
    <property name="url" value="${oracle.url}"/>
    <property name="username" value="${oracle.username}"/>
    <property name="password" value="${oracle.password}"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

并且a.properties和b.properties文件与app-config.xml位于同一位置...

我发现在运行测试时,属性占位符(文字"$ {property}")是发送到oracle服务器而不是属性文件中的值.

我也尝试使用PropertyPlaceholderConfigurer而不是bean配置,但它仍然找不到/包含属性.

我正在使用eclipse helios,spring 3.0.5,最新版本m2eclipse和4.4 junit.我不得不降级junit以获得不同的maven/junit bug.

在tomcat中发布时,将读取并正确使用这些属性.我只在运行junit测试时看到问题.

Ral*_*lph 6

根据你的例外情况:

org.springframework.jdbc.CannotGetJdbcConnectionException:无法获取JDBC连接; 嵌套异常是org.apache.commons.dbcp.SQLNestedException:无法创建PoolableConnectionFactory(ORA-01017:用户名/密码无效;登录被拒绝

您的问题不是找不到属性,如果找不到属性,则异常就是这样 org.springframework.beans.factory.BeanDefinitionStoreException: ... Could not resolve placeholder 'oracle.username'

这是因为您需要配置PropertyPlaceholderConfigurer而不是PropertiesFactoryBean(这就是util:properties所做的http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring- framework-reference.html#xsd-config-body-schemas-util-properties)

<bean id="propertyPlaceHolderConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:spring/a.properties</value>
                <value>classpath:spring/a.properties</value>
            </list>
        </property>
    </bean>
Run Code Online (Sandbox Code Playgroud)


小智 0

看来你正在使用maven。了解您将文件放在哪里会有所帮助。按照惯例,属性文件的测试版本应位于 src/test/resources/ 中,生产版本应位于 src/main/resources 中。它们应该会自动解决。