简体   繁体   English

Spring PropertySource在JUnit测试中不起作用

[英]Spring PropertySource not working in JUnit Test

I am facing issue while running JUnit test case. 我在运行JUnit测试用例时遇到问题。

Problem is, When I run application as web application then @PropertySource works fine by injecting all properties from xml file but when I run the application as JUnit then I am getting error as "Could not resolve placeholder". 问题是,当我运行应用程序作为Web应用程序,然后@PropertySource的工作原理是注射从XML文件中的所有性能优良,但是当我运行应用程序的JUnit然后我收到错误为“无法解析占位符”。

web.xml web.xml中

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:resources/applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:resources/spring-mvc-context.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

DAO Class DAO类

@Configuration
@PropertySource("classpath:resources/shore-dal_queries.xml")
public class SpringShoreDao extends SpringBaseDao implements ShoreDao {

    @Value("${shore.getAllShores}")
    private String getShoresQuery;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Override
    public Optional<List<Shore>> getAllShores() throws DataAccessException {
        Optional<List<Shore>> shoreList = null;
        try {
            List<Shore> tempList = (getNamedParameterJdbcTemplate().query(getShoresQuery, new ShoreRowMapper()));
            shoreList = Optional.of(tempList);
        }
        catch (org.springframework.dao.DataAccessException e) {
        }
        return shoreList;
    }
}

XML File XML文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="shore.getAllShores">
        <![CDATA[
            SELECT shoreID, shoreName, isActive, updatedBy, updatedDate, createdBy, createdDate
            FROM shore
        ]]>
    </entry>
</properties>

JUnit Test Class JUnit测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
        "classpath:resources/applicationContext.xml",
        "classpath:resources/spring-mvc-context.xml"})
public class SpringShoreDaoTest {


    @Autowired
    ShoreDao shoreDao; 

    @Test
    public void testGetAllShores() throws DataAccessException {
        List<Shore> listShore= shoreDao.getAllShores();
        ............  
    }
}

spring-mvc-context.xml 弹簧MVC-context.xml中

  <annotation-driven />
    <context:annotation-config />
    <context:component-scan base-package="com.abc.him.utmc" />     
    <resources mapping="/resources/**" location="/resources/" />

    <beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <beans:property name="messageConverters">
            <beans:list>
                <beans:ref bean="jsonMessageConverter"/>
            </beans:list>
        </beans:property>
    </beans:bean>

    <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </beans:bean> 

applicationContext.xml applicationContext.xml中

<context:annotation-config />
<context:property-placeholder location="classpath:resources/db.properties"/>
... DB related beans

When I run the JUnit Test File, I am getting exception as, 运行JUnit测试文件时,出现异常,

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'shore.getAllShores' in string value "${shore.getAllShores}"

while everything works fine when I run the same project as Web Application. 当我运行与Web应用程序相同的项目时,一切正常。

You can define PropertySourcesPlaceholderConfigurer in test configuration and set your resources/shore-dal_queries.xml as resource to it (there is nice example here ). 您可以定义PropertySourcesPlaceholderConfigurer测试配置和设置您的resources/shore-dal_queries.xml作为资源给它(有很好的例子在这里 )。

So try something like this: 所以尝试这样的事情:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class SpringShoreDaoTest {

    @Configuration
    @ImportResource({"classpath:resources/applicationContext.xml",
    "classpath:resources/spring-mvc-context.xml"})   
    static class someConfig {

        // because @PropertySource doesnt work in annotation only land
        @Bean
        public static PropertyPlaceholderConfigurer propConfig() {
            PropertyPlaceholderConfigurer ppc =  new PropertyPlaceholderConfigurer();
            ppc.setLocation(new ClassPathResource("resources/shore-dal_queries.xml"));
            return ppc;
        }

        @Bean
        public SpringShoreDao springShoreDao() {
            //probably you do not need this bean since you have component scan in applicationContext 
            return new SpringShoreDao();
        }
    }


    @Autowired
    SpringShoreDao springShoreDao; 

    @Test
    public void testGetAllShores() throws DataAccessException {
        List<Shore> listShore= shoreDao.getAllShores();
        ............  
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM