是否有一种方便的方法可以强制Grails / Hibernate通过集成测试重新创建数据库架构?

最佳答案

如果在DataSource.groovy中添加以下内容,则将在运行集成测试之前创建一个空数据库:

environments {
    test {
        dataSource {
            dbCreate = "create"
        }
    }
}

默认情况下,每个集成测试都在一个在测试结束时回滚的事务中执行,因此,除非您不使用此默认行为,否则无需以编程方式重新创建数据库。

更新资料

根据您的评论,您似乎确实希望在进行一些集成测试之前重新创建架构。在这种情况下,我唯一能想到的就是跑步
  • 删除并重新创建模式
  • 使用grails schema-export导入新的架构

  • class MyIntegrationTest {
    
        SessionFactory sessionFactory
    
        /**
         * Helper for executing SQL statements
         * @param jdbcWork A closure that is passed an <tt>Sql</tt> object that is used to execute the JDBC statements
         */
        private doJdbcWork(Closure jdbcWork) {
    
            sessionFactory.currentSession.doWork(
    
                new Work() {
                    @Override
                    void execute(Connection connection) throws SQLException {
    
                        // do not close this Sql instance ourselves
                        Sql sql = new Sql(connection)
                        jdbcWork(sql)
                    }
                }
            )
        }
    
        private recreateSchema() {
    
            doJdbcWork {Sql sql ->
               // use the sql object to drop the database and create a new blank database
               // something like the following might work for MySQL
               sql.execute("drop database my-schema")
               sql.execute("create database my-schema")
            }
    
            // generate the DDL and import it
            // there must be a better way to execute a grails command from within an
            // integration test, but unfortunately I don't know what it is
            'grails test schema-export export'.execute()
        }
    
        @Test
        void myTestMethod() {
            recreateSchema()
            // now do the test
        }
    }
    

    首先,此代码是未经测试的,因此请高度怀疑和低期望。其次,您可能需要更改集成测试的默认转换行为(使用@Transactional)才能使其正常工作。

    关于testing - Grails-重新创建数据库架构以进行集成测试,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16628929/

    10-12 02:36