Unitils结合Dbdeploy管理测试数据库

Unitils是单元测试的一组工具集,介绍见http://www.iteye.com/topic/160004

Dbdeploy是Thoughtworks公司开发的数据库工具,获得Jolt大奖。 

Unitils有自己的一个管理类似于dbdeploy的管理数据库的module -- DBMaintainer,其要求的sql文件名称格式如下所示,要求使用下划线分隔

001_create_users_table.sql

Dbdeploy要求的sql文件格式使用空格分隔

1 create users table.sql

如果在项目中同时使用了dbdeploy和unitils(dbdeploy比dbmaintainer更强大,同时支持undo),由于两种格式不匹配,就需要维护两套sql文件,比较麻烦。目前在dbdeploy中没有发现可以配置文件名的方法,只能从unitils入手,查看unitils的文档找到解决方法。

使用unitils时可以自定义ScriptSource(获取sql file source的一个接口),在unitils.properties中加入

org.unitils.dbmaintainer.script.ScriptSource.implClassName=com.andyao.unitils.DbDeployScriptSource

 DbDeployScriptSource为

public class DbDeployScriptSource extends FileScriptSource {

    public static final String SEPARATOR = " ";


    /**
     * Indicates if the given file is regarded as a script file
     *
     * @param file                    The file
     * @param scriptFileSpecification Specification describing the files that can be regarded as a script file
     * @return True if the given file is regarded as a script file.
     */
    @Override
    protected boolean isScriptFile(File file, ScriptFilesSpecification scriptFileSpecification) {
        String name = file.getName();
        boolean fileExtensionSupported = false;
        for (String fileExtension : scriptFileSpecification.getFileExtensions()) {
            if (name.endsWith(fileExtension)) {
                fileExtensionSupported = true;
                break;
            }
        }
        if (!fileExtensionSupported) {
            return false;
        }

        if (scriptFileSpecification.isExcludeFilesWithoutIndex()) {
            if (!StringUtils.contains(name, SEPARATOR)) {
                return false;
            }
            String indexNrStr = StringUtils.substringBefore(name, SEPARATOR);
            if (!StringUtils.isNumeric(indexNrStr)) {
                return false;
            }
        }
        return true;
    }

    /**
     * Returns the version index of the given script file
     *
     * @param scriptFile The file containing a script
     * @return The version of the script file
     */
    @Override
    protected Long getIndex(File scriptFile) {
        if (StringUtils.contains(scriptFile.getName(), SEPARATOR)) {
            try {
                return new Long(StringUtils.substringBefore(scriptFile.getName(), SEPARATOR));
            } catch (NumberFormatException e) {
                return -1L;
            }
        } else {
            return -1L;
        }
    }
}
 这样就可以同时使用dbdeploy和unitils,做到自动化维护测试数据库。

猜你喜欢

转载自andyao.iteye.com/blog/180231
今日推荐