使用springboottest和h2来构建数据库测试的采坑记录

文章目录

现状

因为项目关系和人力关系, 代码写的比较快而且质量不是很好. bug比较多 基本功能总是有问题(某些场景下) 所以现在想快速补齐测试短板.

为啥要做

想看看如何将spring boot test + db这套结合起来做测试… 因为我们是saas项目 所以更多的想法就是能不能采用内存数据库来方便UAT测试. 所以就有了下面的数据库对比和h2采坑记录

不同数据库对比:

  H2 Derby HSQLDB MySQL PostgreSQL
Pure Java Yes Yes Yes No No
Memory Mode Yes Yes Yes No No
Encrypted Database Yes Yes Yes No No
ODBC Driver Yes No No Yes Yes
Fulltext Search Yes No No Yes Yes
Multi Version Concurrency Yes No Yes Yes Yes
Footprint (embedded) ~2 MB ~3 MB ~1.5 MB
Footprint (client) ~500 KB ~600 KB ~1.5 MB ~1 MB ~700 KB

我们的效果

依赖springboot test 可以很方便的对整个应用的各个层级的代码做测试而且不用担心有问题

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
//...
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

//@Ignore
@RunWith(SpringRunner.class)
@SpringBootTest
public class UseMemDbDerbyTest {

    Log LOG = LogFactory.getLog(UseMemDbDerbyTest.class);
    
    // 可以在这里做一些针对UAT测试的一些设置啥的
    static {
        Constants.COREDB = "testdb";
        System.setProperty("kb.config", "/Users/edward/projects/kb/config/kb-local-uat.config");
        try {
            LayeredConf.getInstance().load(System.getProperty("kb.config"));
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

// 自动注入的对象  可以很方便的拿来测试 只要是被springboot管理的
    @Autowired
    AccountService accountService;

    @Autowired
    RpcSessionController addSessionController;

    @Test
    public void test() throws Exception {
        LOG.info("Step 1: prepare account");
        Account a = prepareAccount();
    }
    
        Account prepareAccount() {
        AccountCatalog.initialize();
        accountService.delete(Account.getExternalId(Environment.ACCOUNT_ID_TEST));
        JSONObject o = new JSONObject();
        o.put("name", "PerfTest");
        return accountService.create(o.toString());
    }
    
}