DBunit and Spring TestContext practices

Source: Internet
Author: User

1. Define the interface UserDao. javapackage com. bao. dbunit. dao;

Import com. bao. dbunit. entity. User;

Public interface UserDao {
Public User getUserByNick (String nick );

Public void save (User user );

Public void update (User user );

Public void remove (String nick );
} Pojo class: User. javapackage com. bao. dbunit. entity;

Public class User {
Private String nick;
Private String password;

Public String getNick (){
Return nick;
}

Public void setNick (String nick ){
This. nick = nick;
}

Public String getPassword (){
Return password;
}

Public void setPassword (String password ){
This. password = password;
}

} 2. Implementation interface 1) Help class: BaseDao. javapackage com. bao. dbunit. dao. impl;

Import org. springframework. jdbc. core. support. JdbcDaoSupport;

Public class BaseDao extends JdbcDaoSupport {

} 2) implementation class: DefaultUserDao. javapackage com. bao. dbunit. dao. impl;

Import java. SQL. ResultSet;
Import java. SQL. SQLException;
Import org. springframework. jdbc. core. RowMapper;
Import com. bao. dbunit. dao. UserDao;
Import com. bao. dbunit. entity. User;

Public class DefaultUserDao extends BaseDao implements UserDao {

Private static String QUERY_BY_NICK = "select * from user where user. nick =? ";

Private static String REMOVE_USER = "delete from user where user. nick =? ";

Private static String INSERT_USER = "insert into user (nick, password) values (?, ?) ";

Private static String UPDATE_USER = "update user set user. password =? Where user. nick =? ";
@ Override
Public User getUserByNick (String nick ){
Return (User) getJdbcTemplate (). queryForObject (QUERY_BY_NICK, new Object [] {nick}, new RowMapper (){
@ Override
Public Object mapRow (ResultSet rs, int index) throws SQLException {
User user = new User ();
User. setNick (rs. getString ("nick "));
User. setPassword (rs. getString ("password "));
Return user;
}
});
}

@ Override
Public void remove (String nick ){
GetJdbcTemplate (). update (REMOVE_USER, new Object [] {nick });
}

@ Override
Public void save (User user ){
GetJdbcTemplate (). update (INSERT_USER, new Object [] {user. getNick (), user. getPassword ()});
}

@ Override
Public void update (User user ){
GetJdbcTemplate (). update (UPDATE_USER, new Object [] {user. getPassword (), user. getNick ()});
}

} 3. Related configuration: applicationContext. xml <? 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: tx = "http://www.springframework.org/schema/tx"
Xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
Http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd ">

<Bean name = "dataSource" class = "org. springframework. jdbc. datasource. DriverManagerDataSource">
<Property name = "driverClassName" value = "com. mysql. jdbc. Driver"> </property>
<Property name = "url" value = "jdbc: mysql: // localhost/dbunit"> </property>
<Property name = "password" value = "root"/>
<Property name = "username" value = "root"/>
</Bean>

<Bean name = "jdbcTemplate" class = "org. springframework. jdbc. core. JdbcTemplate">
<Property name = "dataSource" ref = "dataSource"/>
</Bean>

<Bean name = "baseDao" abstract = "true" class = "com. bao. dbunit. dao. impl. BaseDao">
<Property name = "jdbcTemplate" ref = "jdbcTemplate"/>
</Bean>

<Bean name = "userDao" parent = "baseDao" class = "com. bao. dbunit. dao. impl. DefaultUserDao"/>

</Beans>
SQL Script: ddl. sqlcreate table user (
Nick varchar (12) not null,
Password varchar (12) not null,
Primary key (nick)
); 4. perform the test: UserDaoTest. javapackage com. bao. dbunit. dao;

Import javax. SQL. DataSource;

Import org. dbunit. Assertion;
Import org. dbunit. database. DatabaseConnection;
Import org. dbunit. database. IDatabaseConnection;
Import org. dbunit. database. QueryDataSet;
Import org. dbunit. dataset. IDataSet;
Import org. dbunit. dataset. xml. FlatXmlDataSet;
Import org. dbunit. operation. DatabaseOperation;
Import org. junit. Assert;
Import org. junit. Before;
Import org. junit. Test;
Import org. springframework. beans. factory. annotation. Autowired;
Import org. springframework. core. io. ClassPathResource;
Import org. springframework. jdbc. datasource. performanceutils;
Import org. springframework. test. context. ContextConfiguration;
Import org. springframework. test. context. junit4.20.acttransactionaljunit4springcontexttests;
Import org. springframework. test. context. transaction. TransactionConfiguration;

Import com. bao. dbunit. dao. UserDao;
Import com. bao. dbunit. entity. User;


@ ContextConfiguration (locations = {"classpath: testApplicationContext. xml "})
@ TransactionConfiguration (defaultRollback = true)
Public class UserDaoTest extends acttransactionaljunit4springcontexttests {
@ Autowired
Private UserDao userDao;

@ Autowired
Private DataSource;

Private IDatabaseConnection conn;

@ Before
Public void initDbunit () throws Exception {
Conn = new DatabaseConnection (performanceutils. getConnection (dataSource ));
}

@ Test
Public void saveUser () throws Exception {
User user = new User ();
User. setNick ("user001 ");
User. setPassword ("password001 ");
UserDao. save (user );

QueryDataSet actual = new QueryDataSet (conn );
Actual. addTable ("user ",
"Select * from user where user. nick = 'user001 '");

IDataSet expected = new FlatXmlDataSet (new ClassPathResource (
"Com/bao/dbunit/dao/user001.xml"). getFile ());

Assertion. assertEquals (expected, actual );
}

@ Test
Public void updateUser () throws Exception {

IDataSet origen = new FlatXmlDataSet (new ClassPathResource (
"Com/bao/dbunit/dao/user001.xml"). getFile ());

DatabaseOperation.INSERT.exe cute (conn, origen );

User user = new User ();
User. setNick ("user001 ");
User. setPassword ("password002 ");
UserDao. update (user );

QueryDataSet actual = new QueryDataSet (conn );
Actual. addTable ("user ",
"Select * from user where user. nick = 'user001 '");

IDataSet expected = new FlatXmlDataSet (new ClassPathResource (
"Com/bao/dbunit/dao/user0020.updated.xml"). getFile ());

Assertion. assertEquals (expected, actual );
}

@ Test
Public void removeUser () throws Exception {
IDataSet origen = new FlatXmlDataSet (new ClassPathResource (
"Com/bao/dbunit/dao/user001.xml"). getFile ());
DatabaseOperation.INSERT.exe cute (conn, origen );

UserDao. remove ("user001 ");

QueryDataSet actual = new QueryDataSet (conn );
Actual. addTable ("user", "select * from user where nick = 'user001 '");

Assert. assertEquals (0, actual. getTable ("user"). getRowCount ());

}

@ Test
Public void findUser () throws Exception {
IDataSet data = new FlatXmlDataSet (new ClassPathResource (
"Com/bao/dbunit/dao/user001.xml"). getFile ());
DatabaseOperation.INSERT.exe cute (conn, data );


User user = userDao. getUserByNick ("user001 ");

Assert. assertEquals ("password001", user. getPassword ());
}

} Test related configuration files: 1) user001_updated.xml in the com. bao. dbunit. dao package <? Xml version = "1.0" encoding = "UTF-8"?>
<Dataset>
<User nick = "user001" password = "password002"/>
</Dataset> 2) user001.xml in the com. bao. dbunit. dao package <? Xml version = "1.0" encoding = "UTF-8"?>
<Dataset>
<User nick = "user001" password = "password001"/>
</Dataset> 3) testApplicationContext. xml <? 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: tx = "http://www.springframework.org/schema/tx"
Xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
Http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd ">

<Bean name = "dataSource" class = "org. springframework. jdbc. datasource. DriverManagerDataSource">
<Property name = "driverClassName" value = "com. mysql. jdbc. Driver"> </property>
<Property name = "url" value = "jdbc: mysql: // localhost/dbunit"> </property>
<Property name = "password" value = "root"/>
<Property name = "username" value = "root"/>
</Bean>

<Bean name = "transactionManager" class = "org. springframework. jdbc. datasource. cetcetransactionmanager">
<Property name = "dataSource" ref = "dataSource"/>
</Bean>

<Tx: annotation-driven transaction-manager = "transactionManager"/>

<Bean name = "jdbcTemplate" class = "org. springframework. jdbc. core. JdbcTemplate">
<Property name = "dataSource" ref = "dataSource"/>
</Bean>

<Bean name = "baseDao" abstract = "true" class = "com. bao. dbunit. dao. impl. BaseDao">
<Property name = "jdbcTemplate" ref = "jdbcTemplate"/>
</Bean>

<Bean name = "userDao" parent = "baseDao" class = "com. bao. dbunit. dao. impl. DefaultUserDao"/>

</Beans> the test succeeds, and the data in the database is rolled back. Appendix: pom. xml <dependencies>
<Dependency>
<GroupId> org. springframework </groupId>
<ArtifactId> spring </artifactId>
<Version> 2.5.6 </version>
</Dependency>
<Dependency>
<GroupId> mysql </groupId>
<ArtifactId> mysql-connector-java </artifactId>
<Version> 5.1.6 </version>
</Dependency>
<Dependency>
<GroupId> commons-logging </groupId>
<ArtifactId> commons-logging </artifactId>
<Version> 1.1.1 </version>
</Dependency>

<Dependency>
<GroupId> org. springframework </groupId>
<ArtifactId> spring-test </artifactId>
<Version> 2.5.6 </version>
<Scope> test </scope>
</Dependency>
<Dependency>
<GroupId> junit </groupId>
<ArtifactId> junit </artifactId>
<Version> 4.4 </version>
<Scope> test </scope>
</Dependency>
<Dependency>
<GroupId> org. easymock </groupId>
<ArtifactId> easymock </artifactId>
<Version> 2.4 </version>
<Scope> test </scope>
</Dependency>
<Dependency>
<GroupId> org. dbunit </groupId>
<ArtifactId> dbunit </artifactId>
<Version> 2.4.6 </version>
<Scope> test </scope>
</Dependency>
<Dependency>
<GroupId> org. slf4j </groupId>
<ArtifactId> slf4j-nop </artifactId>
<Version> 1.5.6 </version>
<Scope> test </scope>
</Dependency>
</Dependencies>
<Build>
<Plugins>
<Plugin>
<ArtifactId> maven-compiler-plugin </artifactId>
<Configuration>
<Target> 1.6 </target>
<Sources> 1.6 </source>
<Encoding> UTF-8 </encoding>
</Configuration>
</Plugin>
</Plugins>
</Build> Note] 1. ensure the correctness of the loaded dependency, using the outside test-context.jar, may not find the beans configuration file problem, the dependency cannot be found. 2. Spring-based unit test framework construction and distributed data source unit test http://aaronjiu.iteye.com/blog/435574

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.