Unit testing using the in-memory database

Source: Internet
Author: User

Transferred from: https://gerrydevstory.com/2014/04/11/unit-testing-using-mysql-in-memory-database-on-spring/

Original: Unit testing Using in-memory MySQL Database on Spring

Well the title lied, there's no such thing as in-memory MySQL database (or at least I won ' t being using it for this article). Instead I'll use H2 in-memory database setup to run in "MySQL mode"

?
1234 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >  <property name="driverClassName" value="org.h2.Driver"/>  <property name="url" value="jdbc:h2:mem:testdb;MODE=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE" /></bean>

(Thanks to Joensson for sharing this technique on so)

If your app just uses plain JDBC then adding above datasource to your test context would is sufficient, but if your use JPA /hibernate The cost of table setup, scanning etc could be quite significant.

To overcome this can split the test context using @ContextHierarchy annotation.

In the example below I has unit tests for the Daos:accountdaotest and customerdaotest:

?
1234567 @ContextHierarchy Code class= "Java Plain" ({ &NBSP;&NBSP; @ Contextconfiguration ( &NBSP;&NBSP; @ContextConfiguration ( "Accountdaotest-context.xml" @RunWith ( Springjunit4classrunner. class ) public class accountdaotest { }
?
1234567 @ContextHierarchy Code class= "Java Plain" ({ &NBSP;&NBSP; @ Contextconfiguration ( &NBSP;&NBSP; @ContextConfiguration ( "Customerdaotest-context.xml" @RunWith ( Springjunit4classrunner. class ) public class customerdaotest { }

By doing this Spring test-root-context.xml is setup once and reused accross all unit tests. Only put, common to all tests in test-root-context.xml. In my case I put the following:

    • DataSource
    • Entitymanagerfactory
    • TransactionManager
?
1234567891011121314151617 <!-- JDBC Data Source --><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  <property name="driverClassName" value="org.h2.Driver"/>  <property name="url" value="jdbc:h2:mem:testdb;MODE=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE" /></bean><!-- EntityManagerFactory --><bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">  <property name="persistenceUnitName" value="persistenceUnit" />  <property name="dataSource" ref="dataSource" /></bean><!-- Transaction Manager --><bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">  <property name="entityManagerFactory" ref="entityManagerFactory" /></bean>

All test specific components go to their respective context.

Don ' t forget to add <tx:annotation-driven/> If your DAO uses it. This can ' t is placed on test-root-context.xml because I don ' t scan all my DAOs there.

and lastly-ofcourse-you need to make sure your pom.xml have dependency to spring-test, junit and H2

?
1234567891011121314151617181920 <dependency>  <groupId>com.h2database</groupId>  <artifactId>h2</artifactId>  <version>1.3.176</version>  <scope>test</scope></dependency><dependency>  <groupId>org.springframework</groupId>  <artifactId>spring-test</artifactId>  <version>${org.springframework-version}</version>  <scope>test</scope></dependency><dependency>  <groupId>junit</groupId>  <artifactId>junit</artifactId>  <version>4.7</version>  <scope>test</scope></dependency>

Use Java code to configure the bean:

@Configuration
@EnableTransactionManagement (Proxytargetclass = True)
@EnableConfigurationProperties (value = {Jpaproperties.class,datasourceproperties.class})
public class Mfgmasterinmemorydbconfig {

<!--JDBC Data Source--
<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" >
<property name= "Driverclassname" value= "Org.h2.Driver"/>
<property name= "url" value= "JDBC:H2:MEM:TESTDB; Mode=mysql;db_close_delay=-1;db_close_on_exit=false "/>
</bean>
//
//
<!--entitymanagerfactory--
<bean class= "Org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id= "Entitymanagerfactory" >
<property name= "Persistenceunitname" value= "Persistenceunit"/>
<property name= "DataSource" ref= "DataSource"/>
</bean>
//
<!--Transaction Manager--
<bean class= "Org.springframework.orm.jpa.JpaTransactionManager" id= "TransactionManager" >
<property name= "Entitymanagerfactory" ref= "Entitymanagerfactory"/>
</bean>

@Autowired
Private Jpaproperties jpaproperties;

@Bean
Public Jpavendoradapter Jpavendoradapter () {
return new Hibernatejpavendoradapter ();
}

@Bean
Public Entitymanagerfactorybuilder Entitymanagerfactorybuilder () {
return new Entitymanagerfactorybuilder (Jpavendoradapter (), jpaproperties.getproperties (), NULL);
}

@Bean
Public Entitymanager Entitymanger (Entitymanagerfactory factory) {
return Factory.createentitymanager ();
}

@Bean
Public DataSource DataSource (datasourceproperties basedatasourceproperties) {
DataSource DataSource = Datasourcebuilder
. Create (Basedatasourceproperties.getclassloader ())
. Driverclassname ("Org.h2.Driver")
. URL ("JDBC:H2:MEM:TESTDB; Mode=mysql ")
. Username ("sa")
. Password ("")
. build ();;
return dataSource;
}

@Bean Jpatransactionmanager TransactionManager (entitymanagerfactory entitymanagerfactory) {
Jpatransactionmanager Jpatransactionmanager = new Jpatransactionmanager ();
Jpatransactionmanager.setentitymanagerfactory (entitymanagerfactory);
return jpatransactionmanager;
}

@Bean
Public Localcontainerentitymanagerfactorybean entitymanagerfactory (DataSource DataSource, Entitymanagerfactorybuilder builder) {
map<string, object> hibernateprops = new linkedhashmap<> ();
Hibernateprops.putall (Jpaproperties.gethibernateproperties (DataSource));

Return builder
. DataSource (DataSource)
. Packages (User.class.getPackage (). GetName ())
. Properties (Hibernateprops). JTA (False)
. build ();
}
}

Main annotations of the test class:


@RunWith (Springjunit4classrunner.class)
@ContextConfiguration (Classes={mfgmastertestconfiguration.class,mfgmasterinmemorydbconfig.class})
@SpringApplicationConfiguration (classes = mfgmasterdataapplication.class)
public class Mfgmasterdataapplicationtests {

@Autowired
Public DataSource DataSource;

@Before
public void Prepareuser () {
try {
Datasource.getconnection (). Createstatement (). Executeupdate ("INSERT into user (ID, email, password, created_by, Creation_date, Enabled, Update_date, updated_by, version, FirstName, LastName, Language) "
+ "VALUES ( -1, ' [email protected] ', ' system ',-1, ' 2015-03-02 17:36:38 ', 0, NULL, NULL, 0, ' system ', ' system ', ' US ')");
} catch (SQLException e) {
E.printstacktrace ();
}
}

@Test
public void Contextloads () {
System.out.println ("Done");
}

}

Unit testing using the in-memory database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.