Unitils 使用 DbUnit 資料庫單元測試
//-- UserDAO.java --
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Date;
public class UserDAO {
private Connection conn;
public UserDAO(Connection conn) {
super();
this.conn = conn;
}
public void addUser(int id, String name, Date birthday) throws SQLException {
PreparedStatement ps = conn.prepareStatement("insert into user (id, name, birthday) values (?,?,?)");
try {
ps.setInt(1, id);
ps.setString(2, name);
ps.setDate(3, birthday);
ps.executeUpdate();
} finally {
ps.close();
}
}
}
//-- unitils.properties --
database.driverClassName=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/database
database.dialect=mysql
database.userName=
database.password=
//-- UserDAOTest.java --
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.unitils.UnitilsJUnit4TestClassRunner;
import org.unitils.database.annotations.TestDataSource;
import org.unitils.dbunit.annotation.DataSet;
import org.unitils.dbunit.annotation.ExpectedDataSet;
@RunWith(UnitilsJUnit4TestClassRunner.class)
public class UserDAOTest {
private UserDAO userDAO;
@TestDataSource
private DataSource dataSource;
private Connection conn;
@Before
public void setUp() throws Exception {
conn = dataSource.getConnection();
userDAO = new UserDAO(conn);
}
@After
public void tearDown() throws Exception {
conn.close();
}
@DataSet
@Test
@ExpectedDataSet
public void testAddUser() throws SQLException {
userDAO.addUser(2, "John", java.sql.Date.valueOf("1977-11-01"));
}
}
//-- UserDAOTest.xml --
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<user id="1" name="May" birthday="1997-11-13"/>
</dataset>
//-- UserDAOTest.testAddUser-result.xml --
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<user id="1" name="May" birthday="1997-11-13"/>
<user id="2" name="John" birthday="1977-11-01"/>
</dataset>
2008年11月9日
Unitils testing the persistence layer
Unitils
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言