2012-02-21 2 views
1

단위 테스트를 위해 Unitils을 사용하고 있습니다. 나는 속성 파일을 사용하여 데이터 소스로 Spring을 설정했다.Unitils : 스프링에서 데이터베이스 속성을 얻는 방법

나의 질문은 어떻게 Unitils에 대해 동일한 데이터 소스 또는 동일한 속성을 사용할 수 있습니까?

Unitils는 url, user, password 및 driver와 같은 데이터베이스 구성 매개 변수를 사용하여 unitils.properties 클래스 경로에있는 파일을 필요로합니다.

다음과 같이 Spring 구성에서 사용 된 등록 정보를 사용하여 Unitils를 구성하려했지만 작동하지 않습니다.

database.driverClassName=${jdbc.driver.class} 

감사합니다, 안녕

답변

1

다른 접근 방식을 사용했지만 Ryan의 대답은 정확하고 유용합니다.

나는 다음과 같이 메소드를 오버라이드 (override) RO 클래스 PropertiesDataSourceFactory 확장 :

public class UnitilsDataSourceFactory extends PropertiesDataSourceFactory { 

    @Override 
    public void init(Properties configuration) { 
     try { 
      String[] configFiles = new String[] { "applicationContext-test.xml" }; 
      BeanFactory factory = new ClassPathXmlApplicationContext(configFiles); 

      SystemPropertiesReader systemPropertiesReader = (SystemPropertiesReader) factory.getBean("systemPropertiesReader"); 
      Properties loadProperties = systemPropertiesReader.loadProperties(); 

      super.init(loadProperties); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public DataSource createDataSource() { 
     DataSource dataSource = super.createDataSource(); 
     return dataSource; 
    } 

} 

과도 같은 SystemPropertiesReader을 썼다 :

public class SystemPropertiesReader { 

    private Collection<Resource> resources; 

    public void setResources(final Collection<Resource> resources) { 
     this.resources = resources; 
    } 

    public void setResource(final Resource resource) { 
     resources = Collections.singleton(resource); 
    } 

    @PostConstruct 
    public Properties loadProperties() throws Exception { 
     final Properties systemProperties = System.getProperties(); 
     for (final Resource resource : resources) { 
      final InputStream inputStream = resource.getInputStream(); 
      try { 
       systemProperties.load(inputStream); 
      } finally { 
       // 
      } 
     } 

     return systemProperties; 
    } 

} 

및 등록 정보 파일에 빈을 추가 :

<bean id="systemPropertiesReader" class="uk.co.friendslife.eventmanager.domain.dao.SystemPropertiesReader"> 
      <property name="resource"> 
       <value>classpath:/META-INF/em/config/eventmanager_${database_name_lower}.properties</value> 
      </property> 
</bean> 

다음을 unitils.properties에 추가하십시오.

org.unitils.database.config.DataSourceFactory.implClassName=x.y.UnitilsDataSourceFactory 
1

하나의 잠재적 인 해결책은 ... 당신은 당신의 봄 구성이 아닌 다른 방법으로 주위의, unitils.properties에서의 데이터 소스 매개 변수를 읽을 수있을 수 있습니다. 아마도 이상적이지는 않습니다.

저는 unitils가 커버 아래에 스프링을 사용하고 있기 때문에 @SpringApplicationContext을 사용하여 단위 테스트에서 데이터 소스 컨텍스트를 추가 할 수도 있습니다. unitils가 시작할 때 unitils에 의해 설정되는 데이터 소스 빈의 이름을 알아낼 수 있다면, 컨텍스트에서 오버라이드 할 수 있습니다 (다른 스프링 빈이 생성되기 전에 unitils 데이터 소스 빈이 생성되었다고 가정 할 때).

예 :

@SpringApplicationContext({"correctDataSourceContext.xml"})

편집 : https://stackoverflow.com/a/6561782/411229 는 기본적으로 Unitils 자신의 인스턴스를 수동으로 속성을 설정 : 확실히 작동합니다 또 다른 옵션을 선택합니다.

0

단지 아이디어를 추가하고 싶습니다. 모범 사례인지 아니면 확실하지 않은지 잘 모르겠습니다.

  • MYPROJECT
    - SRC
    --TestPackage
    --- BaseServiceTest.class
    --- BlogspotServiceTest.class
    --hibernate.cfg.XML
    -
    --WEB-INF
    ---는 Blogspot - 서블릿-test.xml의
    ---jdbc-test.properties 내 blogspot-을 사용하는 내 경우에는

을 서블릿 test.xml의 호출하거나 이

MY jdbc-test.properties는 파일 데이터 소스

<?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:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:lang="http://www.springframework.org/schema/lang" 
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:util="http://www.springframework.org/schema/util" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd 
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
     http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd 
     http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 
     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> 

    .... some bean configuration 

    <bean id="propertyConfigurer" 
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" 
      p:location="file:web/WEB-INF/jdbc.properties"/> 


    <bean id="dataSource" 
      class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" 
      p:driverClassName="${jdbc.driverClassName}" 
      p:url="${jdbc.databaseurl}" 
      p:username="${jdbc.username}" 
      p:password="${jdbc.password}"/> 

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
     <property name="dataSource" ref="dataSource"/> 
     <property name="configLocation" value="classpath:hibernate.cfg.xml"/> 
     <property name="hibernateProperties"> 
      <props> 
       <prop key="hibernate.dialect">${jdbc.dialect}</prop> 
       <prop key="hibernate.show_sql">true</prop> 
       <prop key="hibernate.hbm2ddl.auto">update</prop> 
      </props> 
     </property> 
    </bean> 

    <!-- DAO'S --> 
    <bean id="blogspotDAO" class="package.BlogspotDAOImpl"/> 

    <!-- SERVICES --> 
    <bean id="blogspotService" class="package.BlogspotServiceImpl"/> 

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
     <property name="sessionFactory" ref="sessionFactory"/> 
    </bean> 


    <tx:annotation-driven transaction-manager="transactionManager"/> 
</beans> 
을 만들

jdbc.driverClassName=com.mysql.jdbc.Driver 
jdbc.dialect=org.hibernate.dialect.MySQL5Dialect 
jdbc.databaseurl=jdbc:mysql://127.0.0.1:3306/dbspringminiblogtest 
jdbc.username=root 
jdbc.password= 
있는 hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE hibernate-configuration PUBLIC 
    "-//Hibernate/Hibernate Configuration DTD//EN" 
    "http://www.hibernate.org/dtd//hibernate-configuration-3.0.dtd"> 

    <hibernate-configuration> 
     <session-factory> 
      <mapping class="somePackage.entity.Author"/> 
      <!-- Other Entity Class to be mapped --> 

     </session-factory> 
    </hibernate-configuration> 

를 들어

나 여러 @SpringApplicationContext 주석의 작성을 완화하고, 또한 다른 클래스를 테스트하는 데 필요한 일반적인 구성을 구성하는 데 사용됩니다 위해 내가 BaseClass로 만들어, 그냥 그것을 확장합니다.

@SpringApplicationContext({"file:web/WEB-INF/blogspot-servlet-test.xml"}) 
public class BaseServiceTest extends UnitilsJUnit4 { 
} 

내가 내 BaseClass로의 데이터 소스 및 기타 콩 구성을로드 할 @SpringApplicationContext 사용이 내가 그것을 구현하는 방법입니다.

다음은 : 프로그램을 실행할 수 있도록 TestPackage 내부 unitils.properties 및 unitils-local.properties을 만드십시오 : 자세한 내용

public class BlogspotServiceTest extends BaseServiceTest{ 

    @Mock 
    @InjectInto(property = "blogspotDAO") 
    @SpringBean("blogspotDAO") 
    private BlogspotDAO blogspotDAOMock; 

    @TestedObject 
    @SpringBean("blogspotService") 
    private BlogspotService blogspotServiceMock; 

    @Test 
    public void testAddBlogSpot() { 
     assertNotNull("BlogspotService Not null",blogspotServiceMock); 
    } 
} 

주에 대한 Spring-Unitils Tutorial 를 참조하십시오. @SpringBean 설명 및 기타 주석에 대한

읽어보십시오

Unitils-EasyMock

관련 문제