junit_dbunit

public class DbUtil {

    public static Connection getConnection() throws SQLException{
        Connection conn=null;
        conn=DriverManager.getConnection("jdbc:postgresql://localhost:5432/itat_junit",
                    "postgres","686991");
        return conn;
    }
    
    public static void close(Connection conn){
        try {
            if(conn!=null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    public static void close(PreparedStatement ps){
        try {
            if(ps!=null) ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    public static void close(ResultSet rs){
        try {
            if(rs!=null) rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

/**dbunit
 * 1.导入dbunit.jar、slf4j-api-1.6.jar
 * 2.配置dbunit的xml文件
 * */
public class TestDbunit {

    /**3.创建dbunit的connection,用来对数据文件进行操作的,
     *         connection必须依赖项目中的JDBC Connection
     * 4.创建IDataSet,用于获取测试中的数据
     * 5.初始化数据,完成数据*/
    @Test
    public void testLoad(){
        testBackupTable();
        try {
            IDatabaseConnection con=new DatabaseConnection(DbUtil.getConnection());
            /*FlatXmlDataSet用于获取基于属性值的xml中的值
             *XmlDataSet用于基于节点的xml数据*/
            /**错误1:t_user.xml一定放到源文件目录!*/
            IDataSet ds=new FlatXmlDataSet(
                    new FlatXmlProducer(
                            new InputSource(
                                    TestDbunit.class.getClassLoader().getResourceAsStream("t_user.xml"))));
            /*将数据库中的数据清空,并且把测试数据插入*/
            DatabaseOperation.CLEAN_INSERT.execute(con, ds);
            /*从Dao中获取数据完成测试*/
            IUserDao ud=new UserDao();
            User tu=ud.load("admin");
            //Assert.assertEquals(tu.getId(),1);
            assertEquals(tu.getId(),1);
            /**错误2:字符串一定要去空格!*/
            assertEquals(tu.getUsername().trim(),"admin");
            assertEquals(tu.getPassword().trim(),"123");
            assertEquals(tu.getNickname().trim(),"超级管理员");
        } catch (DatabaseUnitException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        testResume();
    }
    
    /**备份和还原数据库*/
    @Test
    public void testBackupAllTable(){
        try {
            /*创建dbunit的connection,用来对数据文件进行操作的,
              connection必须依赖项目中的JDBC Connection*/
            IDatabaseConnection con=new DatabaseConnection(DbUtil.getConnection());
            /*根据con创建相应的dataset,这个dataset包含所有的表*/
            IDataSet ds=con.createDataSet();
            /*将ds中的数据通过FlatXmlDataSet的格式备份到xml文件中*/
            FlatXmlDataSet.write(ds,new FileWriter("F:/web/test/dbunit/test.xml"));
        } catch (DatabaseUnitException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**备份单个表*/
    @Test
    public void testBackupTable(){
        try {
            /*创建dbunit的connection,用来对数据文件进行操作的,
              connection必须依赖项目中的JDBC Connection*/
            IDatabaseConnection con=new DatabaseConnection(DbUtil.getConnection());
            /*通过QueryDataSet可以有效地选择要处理的表来作为数据集*/
            QueryDataSet backup=new QueryDataSet(con);
            /*添加t_user这张表作为备份对象*/
            backup.addTable("t_user");
            /*将ds中的数据通过FlatXmlDataSet的格式备份到xml文件中*/
            FlatXmlDataSet.write(backup,new FileWriter("F:/web/test/dbunit/test02.xml"));
        } catch (DatabaseUnitException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**还原数据库*/
    @Test
    public void testResume(){
        try {
            /*创建dbunit的connection,用来对数据文件进行操作的,
              connection必须依赖项目中的JDBC Connection*/
            IDatabaseConnection con=new DatabaseConnection(DbUtil.getConnection());
            /*根据备份文件创建dataset*/
            IDataSet ds=new FlatXmlDataSet(
                    new FlatXmlProducer(
                            new InputSource(
                                    new FileInputStream("F:/web/test/dbunit/test02.xml"))));
            DatabaseOperation.CLEAN_INSERT.execute(con, ds);
        } catch (DataSetException e) {
            e.printStackTrace();
        } catch (DatabaseUnitException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    
    }
}

public class AbstractDbUnitTestCase {

    public static IDatabaseConnection dbunitCon;
    private File tempFile;
    
    @BeforeClass
    public static void init() throws DatabaseUnitException, SQLException{
        dbunitCon=new DatabaseConnection(DbUtil.getConnection());
    } 
    
    @SuppressWarnings("deprecation")
    protected IDataSet createDataSet(String tablename) throws DataSetException{
        InputStream is=AbstractDbUnitTestCase.class
                .getClassLoader().getResourceAsStream("dbunit_xml/"+tablename+".xml");
        Assert.assertNotNull("dbunit的基本数据文件不存在",is);
        return new FlatXmlDataSet(new FlatXmlProducer(new InputSource(is)));
    }
    
    protected void backupAllTable() 
            throws SQLException, DataSetException, IOException{
        IDataSet ds=dbunitCon.createDataSet();
        /*tempFile=File.createTempFile("back",".xml");
        FlatXmlDataSet.write(ds,new FileWriter(tempFile));*/
        writeBackupFile(ds);
    }
    
    protected void backupCustomTable(String[] tablename) 
            throws SQLException, DataSetException, IOException{
        QueryDataSet ds=new QueryDataSet(dbunitCon);
        for(String str:tablename){
            ds.addTable(str);
        }
        writeBackupFile(ds);
    }
    
    protected void backupOneTable(String tablename) 
            throws SQLException, DataSetException, IOException{
        backupCustomTable(new String[]{tablename});
    }
    private void writeBackupFile(IDataSet ds) 
            throws IOException, DataSetException{
        tempFile=File.createTempFile("back",".xml");
        FlatXmlDataSet.write(ds,new FileWriter(tempFile));
    }
    
    protected void resumeTable() 
            throws FileNotFoundException, DatabaseUnitException, SQLException{
        IDataSet ds=new FlatXmlDataSet(
                new FlatXmlProducer(
                        new InputSource(
                                new FileInputStream(tempFile))));
        DatabaseOperation.CLEAN_INSERT.execute(dbunitCon, ds);
    }
    
    @AfterClass
    public static void destory(){
        try {
            if(dbunitCon!=null) dbunitCon.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}


你可能感兴趣的:(junit_dbunit)