每次执行前 MicronautTest 数据源设置不干净
MicronautTest Datasource setup not clean before each execution
我让这个 micronaut 应用程序执行一些基本的数据库查找,只是为了测试框架。我已经使用 flyway 数据库迁移设置了应用程序,运行 在我的测试设置中设置了一个 h2 数据库(生产使用 postgresql)。这用于正确设置模式。
我的存储库是使用用于 jpa 的 Micronaut 数据创建的,所以如果不在完整的 micronaut 上下文中进行测试,我不知道如何创建它。运行
在我的测试中,我尝试在设置方法中插入一些数据,然后再执行一些 spock 测试。当设置有一次 运行 时,我希望它从一个干净的数据源开始,以便下一次测试执行。由于数据将违反唯一约束,因此它失败并在第二个测试 运行 的设置中出现 sql 错误。这是我的代码:
@MicronautTest()
class CompanyRepositoryTest extends Specification {
@Inject
CompanyRepository repository
@Inject
DataSource dataSource
def sql
def setup() {
sql = new Sql(dataSource: dataSource)
sql.execute(dataSql)
}
def 'test company creation' () {
given:
def name = 'test2'
def orgNumber = '1232429045'
when:
def company = repository.save(new Company(name: name, organizationNumber: orgNumber))
then:
company.id != null
}
@Unroll
def 'get company for #desc'() {
when:
Company result = repository.find(id)
then:
name == null ? result == null : name == result.name
where:
id | name | desc
1 | 'test1' | 'existing company'
2 | null | 'non-existing company'
}
def dataSql = """
insert into company(name, organization_number) values
('test1', '1232429045');
"""
我想我可以在执行删除语句的地方创建一个清理块,但我认为这是最后的手段,因为我希望数据源在每次测试之前都是干净的 运行。
经过一夜好眠,答案显而易见。我没有通过 groovy sql 执行 sql,而是使用 entitymanager。然后这按预期工作
@Inject
EntityManager entityManager
def setup() {
entityManager.createNativeQuery(dataSql).executeUpdate();
}
我让这个 micronaut 应用程序执行一些基本的数据库查找,只是为了测试框架。我已经使用 flyway 数据库迁移设置了应用程序,运行 在我的测试设置中设置了一个 h2 数据库(生产使用 postgresql)。这用于正确设置模式。
我的存储库是使用用于 jpa 的 Micronaut 数据创建的,所以如果不在完整的 micronaut 上下文中进行测试,我不知道如何创建它。运行
在我的测试中,我尝试在设置方法中插入一些数据,然后再执行一些 spock 测试。当设置有一次 运行 时,我希望它从一个干净的数据源开始,以便下一次测试执行。由于数据将违反唯一约束,因此它失败并在第二个测试 运行 的设置中出现 sql 错误。这是我的代码:
@MicronautTest()
class CompanyRepositoryTest extends Specification {
@Inject
CompanyRepository repository
@Inject
DataSource dataSource
def sql
def setup() {
sql = new Sql(dataSource: dataSource)
sql.execute(dataSql)
}
def 'test company creation' () {
given:
def name = 'test2'
def orgNumber = '1232429045'
when:
def company = repository.save(new Company(name: name, organizationNumber: orgNumber))
then:
company.id != null
}
@Unroll
def 'get company for #desc'() {
when:
Company result = repository.find(id)
then:
name == null ? result == null : name == result.name
where:
id | name | desc
1 | 'test1' | 'existing company'
2 | null | 'non-existing company'
}
def dataSql = """
insert into company(name, organization_number) values
('test1', '1232429045');
"""
我想我可以在执行删除语句的地方创建一个清理块,但我认为这是最后的手段,因为我希望数据源在每次测试之前都是干净的 运行。
经过一夜好眠,答案显而易见。我没有通过 groovy sql 执行 sql,而是使用 entitymanager。然后这按预期工作
@Inject
EntityManager entityManager
def setup() {
entityManager.createNativeQuery(dataSql).executeUpdate();
}