小飞知识库 | YeLu🤠MiLu🤪 小飞知识库 | YeLu🤠MiLu🤪
  • 函数式编程
  • Spring
  • SpringMVC
  • SpringBoot
  • SpringCloud
  • Mybatis
  • JVM
  • JUC并发编程
  • 设计模式
  • 单元测试
  • Redis
  • RabbitMQ
  • mysql
  • oracle
  • linux
  • nginx
  • docker
  • elasticSearch
  • windows
  • 虚拟机
  • 监控系统
  • https
  • 内网穿透
  • 前端文章

    • JavaScript
  • 页面

    • HTML
    • CSS
  • 学习笔记

    • 《JavaScript教程》
    • 《JavaScript高级程序设计》
    • 《ES6 教程》
    • 《Vue》
    • 《React》
    • 《TypeScript 从零实现 axios》
    • TypeScript
    • JS设计模式总结
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 版本管理

    • Git笔记
  • 项目构建

    • maven
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
  • JAR包相关
  • 关于
  • 收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

YeLu

爱技术的YeLu🤠
  • 函数式编程
  • Spring
  • SpringMVC
  • SpringBoot
  • SpringCloud
  • Mybatis
  • JVM
  • JUC并发编程
  • 设计模式
  • 单元测试
  • Redis
  • RabbitMQ
  • mysql
  • oracle
  • linux
  • nginx
  • docker
  • elasticSearch
  • windows
  • 虚拟机
  • 监控系统
  • https
  • 内网穿透
  • 前端文章

    • JavaScript
  • 页面

    • HTML
    • CSS
  • 学习笔记

    • 《JavaScript教程》
    • 《JavaScript高级程序设计》
    • 《ES6 教程》
    • 《Vue》
    • 《React》
    • 《TypeScript 从零实现 axios》
    • TypeScript
    • JS设计模式总结
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 版本管理

    • Git笔记
  • 项目构建

    • maven
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
  • JAR包相关
  • 关于
  • 收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 函数式编程

  • spring

  • springMVC

  • springCloud

  • jvm

  • JUC并发编程

  • mybatis

  • 设计模式

  • 📒springBoot

  • 单元测试

    • 单元测试问题
    • Junit的使用
    • dbunit的使用
      • 导包
      • 编写DAO代码
      • 编写数据库访问帮助类
      • 编写基类
      • 编写测试类
    • spring的测试
    • spring整合dbunit
    • easymock的使用
  • java
  • 单元测试
YeLu🤠
2025-01-16
目录

dbunit的使用

参考demo:G:\学习资料\java\java学习文档\java技术文档\Spring文档\xufei-spring-word\xufei-projo-test =》dbunit

dbunit是用来干嘛的呢? 简单的说 dbunit的主要的功能就是用来做DAO层的测试

不是 dbutils(DAO层的解决方案) 、dbunit(专门用来测试DAO层的框架)

# 导包

         <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.6</version>
        </dependency>

        <!--DAO层测试的这个框架包-->
        <dependency>
            <groupId>org.dbunit</groupId>
            <artifactId>dbunit</artifactId>
            <version>2.5.3</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.22</version>
        </dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 编写DAO代码

public class UserDAO {
    /**
     * 通过id找用户
     *
     * @param id
     * @return
     */
    public User findUserById(int id) throws SQLException {
        User user = queryRunner().query("select * from t_user where uId=?", new BeanHandler<User>(User.class), id);
        return user;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12

# 编写数据库访问帮助类

public class JdbcUtils {

    private static DruidDataSource dataSource = null;

    static {
        dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3369/xx?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true&rewriteBatchedStatements=true");
        dataSource.setUsername("root");
        dataSource.setPassword("xxx");
    }

    /**
     * 这个是获取咋们的操作数据库的对象
     *
     * @return
     */
    public static QueryRunner queryRunner() {
        return new QueryRunner(dataSource);
    }

    /**
     * 获取咋们的连接
     *
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }


}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

# 编写基类

public class AbstractDbunitTestCase {

    private DatabaseConnection connection;
    private File tempFile;
    private IDataSet testDataSet;    // 测试数据的DataSet对象

    public AbstractDbunitTestCase(Connection connection, String testFileName) throws DatabaseUnitException {
        this.connection =  new DatabaseConnection(connection);
        InputStream inputStream = AbstractDbunitTestCase.class.getClassLoader().getResourceAsStream(testFileName);
        testDataSet = new FlatXmlDataSet(new FlatXmlProducer(new InputSource(inputStream)));
    }

    public AbstractDbunitTestCase(String testFileName) throws DatabaseUnitException {
        InputStream inputStream = AbstractDbunitTestCase.class.getClassLoader().getResourceAsStream(testFileName);
        testDataSet = new FlatXmlDataSet(new FlatXmlProducer(new InputSource(inputStream)));
    }


    /**
     * 设置这个连接池的包裹对象
     *
     * @param conn
     * @throws DatabaseUnitException
     */
    protected void setDatabaseConnection(Connection conn) throws DatabaseUnitException {
        this.connection = new DatabaseConnection(conn);
    }

    /**
     * 这个就是备份多张表
     *
     * @param tabNames
     */
    protected synchronized void backManyTable(String... tabNames) throws Exception {

        QueryDataSet queryDataSet = new QueryDataSet(connection);
        for (String tabName : tabNames) {
            queryDataSet.addTable(tabName);
        }
        // 实施备份 使用到临时文件
        tempFile = File.createTempFile("dbunitTest", ".xml");
        // 实施备份
        if (null != tempFile) {
            FlatXmlDataSet.write(queryDataSet, Files.newOutputStream(tempFile.toPath()));
        }
    }


    /**
     * 备份一张表
     */
    protected void backOneTable(String tabName) throws Exception {
        backManyTable(tabName);
    }


    /**
     * 插入测试数据
     */
    protected void insertTestData() throws DatabaseUnitException, SQLException {
        if (null != connection && null != testDataSet) {
            DatabaseOperation.CLEAN_INSERT.execute(connection, testDataSet);
        } else {
            throw new RuntimeException("参数有误不能插入数据:");
        }
    }

    /**
     * 还原表中的数据
     */
    protected void resumeTable() throws Exception {
        if (null != tempFile) {
            IDataSet dataSet = new FlatXmlDataSet(new FlatXmlProducer(new InputSource(Files.newInputStream(tempFile.toPath()))));
            DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);
        } else {
            throw new RuntimeException("临时文件都没有怎么还原....");
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79

# 编写测试类

public class TestUserDAO1 extends AbstractDbunitTestCase {

    private UserDAO userDAO;
    private User exUser;

    public TestUserDAO1() throws SQLException, DatabaseUnitException {
        super(JdbcUtils.getConnection(), "testdata.xml");
    }


    @Before
    public void init() throws Exception {
        userDAO = new UserDAO();
        exUser = new User(1, "xff", "123");
        backOneTable("t_user");
        insertTestData();
    }


    @Test
    public void testFindUserById() throws SQLException {
       //进行业务逻辑测试
        User userResult = userDAO.findUserById(1);
        Assert.assertEquals(exUser.getUId(), userResult.getUId());
        Assert.assertEquals(exUser.getUName(), userResult.getUName());
        Assert.assertEquals(exUser.getPassWord(), userResult.getPassWord());
    }


    @After
    public void destory() throws Exception {
        resumeTable();
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#单元测试#dbunit
最近更新: 2025/01/22, 13:46:16
Junit的使用
spring的测试

← Junit的使用 spring的测试→

最近更新
01
服务端配置
07-30
02
frp 安装
07-30
03
Prometheus采集Springboot应用
02-20
更多文章>
Theme by Vdoing | Copyright © 2019-2025 | YeLu🤠MiLu🤪 | MIT License 蜀ICP备2024116879号 | 川公网安备51012202001998号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
欢迎你,我的朋友
看板娘