java使用jUnit,jMockit,dbunit做DAO层单元测试方法

第一步:准备数据

先在MySQL数据库中填写测试数据和期望数据,然后导出到xml文件中。

全表导出:DBUnitHelper.exportTable("t_dp_content_02001", TEST_DATA_FILE);

条件查询导出:DBUnitHelper.exportQueryTable("t_dp_content_02001","select * from t_dp_content_02001 where id=123020011", TEST_DATA_FILE);

xml文件路径举例:private static final String TEST_DATA_FILE = "src/test/resources/testdata/t_dp_content_02001.xml";

第二步:单元测试前清理数据

在执行单元测试前,需要准备测试数据,清理库表:

调用DBUnitHelper.doCleanInsert(xml文件路径)方法将测试数据导入到数据库中,该方法不会删除测试数据以外的其它数据;

调用DBUnitHelper.deleteData(xml文件路径)方法,将测试过程中产生的新数据也删除;

也可以调用DBUnitHelper.doCleanTable(库表名)来清空库表。

代码举例:

@BeforeClass
public static void setUp() throws Exception {
     Mockit.setUpMocks();

     try {

          // 删除并重新插入测试数据
          DBUnitHelper.doCleanInsert(TEST_DATA_FILE);

          // 删除测试过程中产生的新数据
          DBUnitHelper.deleteData(EXPECT_DATA_FILE_1);

      } catch (Throwable e) {

          e.printStackTrace();
      }
}

第三步:编写单元测试用例

调用DAO层的方法,然后调用BaseDaoTest.assertEquals(期望数据文件,SQL语句,库表名,忽略比较的字段)方法判断数据库的数据变化是否符合预期。

判断方法举例:

super.assertEquals(EXPECT_DATA_FILE_1,"select * from t_dp_content_02001 where id=3210200110", "t_dp_content_02001",new String[] {"logicKey", "lastUpdateTime"});

单元测试环境 pom.xml文件


      com.panguso
      pg-app-core
      2.0.0-SNAPSHOT





     junit
    junit
    4.10
    test


    commons-dbcp
    commons-dbcp
    1.4
    test


    org.dbunit
    dbunit
    2.4.8
    test

dbunit.properties配置文件(src/test/resources目录下)

######################################################
drivers=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://10.10.160.157:3306/opendata_unit?useUnicode=true&characterEncoding=utf8
jdbc.maxconn=5
jdbc.user=opendata_unit
jdbc.password=opendata_unit_123
schema=opendata_unit
######################################################
sqlMapFilePath=sqlMapConfig_unit.xml

代码:

BaseContentDaoTest .java

package com.panguso.op.resource.core.dao;

import junit.framework.Assert;
import mockit.Expectations;
import mockit.Mocked;
import mockit.Mockit;

import org.junit.BeforeClass;
import org.junit.Test;

import com.panguso.app.core.test.BaseDaoTest;
import com.panguso.app.core.test.DBUnitHelper;
import com.panguso.app.core.util.RandomUtil;
import com.panguso.op.resource.core.dao.impl.PlainSequenceGenerator;
import com.panguso.op.resource.core.po.Content;

/**
 * 
 * @author yangjianfei
 * @date 2012-11-22
 */
public class BaseContentDaoTest extends BaseDaoTest {
    private static BaseContentDao contentDao;
    private static final String TEST_DATA_FILE = "src/test/resources/testdata/t_dp_content_02001.xml";
    private static final String EXPECT_DATA_FILE_1 = "src/test/resources/testdata/expectation/t_dp_content_02001_1.xml";
    private static final Long ID = 3210200110L;

    @BeforeClass
    public static void setUp() throws Exception {
        Mockit.setUpMocks();

        try {
            ISequenceGenerator generator = new PlainSequenceGenerator(sqlMap);
            contentDao = new BaseContentDao(sqlMap, generator);

            DBUnitHelper.doCleanInsert(TEST_DATA_FILE);
            DBUnitHelper.deleteData(EXPECT_DATA_FILE_1);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    @Mocked
    PlainSequenceGenerator sequenceGenerator;

    @Test
    public void testCRUD() {
        new Expectations() {
            {
                sequenceGenerator.getNextSequence(anyString);
                result = ID;
                times = 1;
            }
        };

        Content content = contentDao.getBaseInfoById(123020011L);
        content.setId(null);
        content.setLogicKey(RandomUtil.generateLetterStr(10));

        // 插入数据
        contentDao.saveBaseInfo(content);
        Content content1 = contentDao.getBaseInfoById(ID);
        Assert.assertEquals(content.getContentState(), content1.getContentState());
        super.assertEquals(EXPECT_DATA_FILE_1,
                "select * from t_dp_content_02001 where id=3210200110", "t_dp_content_02001",
                new String[] {"logicKey", "lastUpdateTime"});

    }

    public static void main(String[] args) throws Exception {
//      DBUnitHelper.exportTable("t_dp_content_02001", TEST_DATA_FILE);
        DBUnitHelper.exportQueryTable("t_dp_content_02001",
                "select * from t_dp_content_02001 where id=123020011", TEST_DATA_FILE);
//      DBUnitHelper.doCleanInsert(TEST_DATA_FILE);
//      DBUnitHelper.deleteData(TEST_DATA_FILE);
//      DBUnitHelper.doInsert(TEST_DATA_FILE);
    }
}

sqlMapConfig.xml文件:

xml version="1.0" encoding="UTF-8"?>


     cacheModelsEnabled="true" enhancementEnabled="true"
        lazyLoadingEnabled="true" errorTracingEnabled="false" maxRequests="32"
        maxSessions="10" maxTransactions="5" useStatementNamespaces="true" />
     type="JDBC" commitRequired="false">
         type="dbcp">
             name="JDBC.Driver" value="com.mysql.jdbc.Driver" />
             name="JDBC.ConnectionURL" value="jdbc:mysql://10.10.160.157:3306/opendata_unit?useUnicode=true&characterEncoding=utf8" />
             name="JDBC.Username" value="opendata_unit" />
             name="JDBC.Password" value="opendata_unit_123" />
             name="Pool.MaximumActiveConnections" value="2" />
             name="Pool.MaximumIdleConnections" value="1" />
             name="Pool.MaximumCheckoutTime" value="120000" />
             name="Pool.TimeToWait" value="500" />
             name="Pool.PingQuery" value="select 1 from t_userinfo" />
             name="Pool.PingEnabled" value="false" />
             name="Pool.PingConnectionsOlderThan" value="1" />
             name="Pool.PingConnectionsNotUsedFor" value="1" />
        
    

     resource="com/panguso/op/resource/core/dao/sql/ResourceSQL.xml" />
     resource="com/panguso/op/resource/core/dao/sql/ContentSQL.xml" />
     resource="com/panguso/op/resource/core/dao/sql/SequenceSQL.xml" />
     resource="com/panguso/op/resource/core/dao/sql/MetaDataSQL.xml" />
     resource="com/panguso/op/resource/core/dao/sql/DataPartnerSQL.xml" />
     resource="com/panguso/op/resource/core/dao/sql/ResourceContentListenerSQL.xml" />
  

你可能感兴趣的:(Djunit)