亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

怎么做MYSQL代碼的單元測試呢?有個好辦法

標簽:
單元測試

数据库相关单元测试代码怎么做?

对于一个重度耦合系统的数据库DAO部分的单元测试怎么来做呢?Mock? 很难吧,而且你怎么测试出这个SQL写的对还是不对。

下面介绍一个很好的jar,可以实现内存中启动数据库,这样单元测试就简单多了。

添加依赖

<dependency>
    <groupId>ch.vorburger.mariaDB4j</groupId>
    <artifactId>mariaDB4j</artifactId>
    <version>2.2.3</version>
</dependency>

怎么使用呢?

  1. 配置DB
DBConfigurationBuilder configBuilder = DBConfigurationBuilder.newBuilder();
configBuilder.setPort(3306); 
configBuilder.setDataDir("/home/theapp/db"); 
DB db = DB.newEmbeddedDB(configBuilder.build());
  1. 启动DB
db.start();
  1. 准备测试数据
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
db.source("path/to/resource.sql");
  1. 单元测试
@Test
public void testGetType() throws Exception {
		//prepare data
		Connection conn = null;
        try {
            conn = DriverManager.getConnection(getConfig().getURL(getDbName()), "root", "");
            QueryRunner qr = new QueryRunner();
            // Should be able to insert into a table
            qr.update(conn, "INSERT INTO `test` (`id`, `type`,value) VALUES (NULL, 'haha', '300');");
        } finally {
            DbUtils.closeQuietly(conn);
        }
		
		//test
		dao = (DaoImpl) SpringContextUtil.getBean("Dao");
		Map<String, String> typeValueMap = dao.getType();
		String value =  typeValueMap.get("haha");
		Assert.assertEquals("300", value);
		
		//delete data
		try {
            conn = DriverManager.getConnection(getConfig().getURL(getDbName()), "root", "");
            QueryRunner qr = new QueryRunner();
            // Should be able to insert into a table
            qr.update(conn, "delete from `test` where type='haha'");
        } finally {
            DbUtils.closeQuietly(conn);
        }
	}

怎么样,是不是既简单有给力呢。

點擊查看更多內容
1人點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消