How to use hsqldb to test DB operation

sometime we want to test dao operation in junit test, below we will use hsqldb to test it.

1. setup hsqldb configuation.

we have a persistent-config.xml like this:

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

    <!-- import the dataSource definition -->
	<import resource="inverter-datasource-config.xml"/>
	<bean id="jpa.repo.statistic" class="com.eifesun.monitor.inverter.persistent.repository.jpa.JpaInverterRepositoryImpl">
	 	<property name="entityManager">
		 	<bean class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
	            <property name="persistenceUnitName" value="inverterdb" />
	        </bean>
        </property>
	</bean>

     <!-- enables scanning for @Transactional annotations -->
    <tx:annotation-driven />
 
	
	<!-- ==================		 3 Profiles to choose from 			=================== 
									- default (uses JPA)
									- jdbc (uses Spring" JdbcTemplate)
									- spring-data-jpa	
		  =============================================================================-->
	
        <!-- JPA EntityManagerFactory -->
        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
              p:dataSource-ref="dataSource">
            <property name="jpaVendorAdapter">
                <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
                      p:database="${jpa.database}" p:showSql="${jpa.showSql}"/>
            </property>
            <!-- gDickens: BOTH Persistence Unit and Packages to Scan are NOT compatible, persistenceUnit will win -->
            <property name="persistenceUnitName" value="inverterdb"/>
            <property name="packagesToScan" value="com.eifesun.monitor.inverter.persistent"/>
        </bean>

        <!-- Transaction manager for a single JPA EntityManagerFactory (alternative to JTA) -->
        <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
              p:entityManagerFactory-ref="entityManagerFactory"/>
        <!--
            Post-processor to perform exception translation on @Repository classes (from native
            exceptions such as JPA PersistenceExceptions to Spring's DataAccessException hierarchy).
        -->
        <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>


        <!--
            Loads JPA beans
            Will automatically be transactional due to @Transactional.
            EntityManager will be auto-injected due to @PersistenceContext.
            PersistenceExceptions will be auto-translated due to @Repository.
        -->
        <context:component-scan base-package="com.eifesun.monitor.inverter.persistent.repository.jpa"/>

</beans>

2. setup cleanup() method to keep each test case isolated.

@After
    public void cleanup() throws SQLException {
        Statement databaseTruncationStatement = null;
        try {
            databaseTruncationStatement = localBean.getDataSource().getConnection().createStatement();
            databaseTruncationStatement.executeUpdate("TRUNCATE SCHEMA public AND COMMIT");
        }
        finally {
            databaseTruncationStatement.close();
        }
    }

3. write test case for each scenario.

   @Test
    public void whenCleanAllInverterTodayOutputEnergyThenAllTodayOutputEnergyWillBeZero() {
        // given
        String inverterId1 = "inverter1";
        String inverterId2 = "inverter2";
        buildAndSaveInverter(inverterId1, 80, 10, 11);
        buildAndSaveInverter(inverterId2, 90, 20, 22);

        // when
        inverterRepo.cleanAllInvertersTodayOutputEnergy();

        // then
        Inverter inverter1 = inverterRepo.findStoredInverter(inverterId1);
        assertThat(inverter1.getEnergyTotal(), equalTo(80L));
        assertThat(inverter1.getOutputPower(), equalTo(10L));
        assertThat(inverter1.getTodayOutputEnergy(), equalTo(0L));

        Inverter inverter2 = inverterRepo.findStoredInverter(inverterId2);
        assertThat(inverter2.getEnergyTotal(), equalTo(90L));
        assertThat(inverter2.getOutputPower(), equalTo(20L));
        assertThat(inverter2.getTodayOutputEnergy(), equalTo(0L));

    }

 

猜你喜欢

转载自sunxboy.iteye.com/blog/2002360
今日推荐