Grails 3.0.9: Spock integration tests' @Rollback annotation is not working

喜你入骨 提交于 2019-12-06 06:17:43

I had the same problem, but in my case, I noticed that everything I load to database with @LoadDataSet is correctly rolled back. But when I have any interaction with a column referenced by a foreign key, @rollback just don't delete the references and this is causing the error. I also tried so many @Transactional solutions, but still doesn't work.

My workaround is to call DomainClassName.executeUpdate('delete from DomainClassName') before the cleanup(), to all domainClasses I am expecting to change. The tests now work, not properly, sadly.

Update:

Check if this works for you.


Just to clarify: I solved my problem using a combination of @Transactional(propagation = Propagation.NESTED) in my test class and then, as the last step of each test, calling DomainClassName.executeUpdate('delete from DomainClassName') to every domain class I'm expecting to change.

My test class is now something like this:

@Integration
@Transactional(propagation = Propagation.NESTED)
@TestFor(MyService)
@LoadDataSet("PathInResources") //If needed
class MyTestSpec extends GebSpec {

  static transactional = true

  @Autowired
  SessionFactory session

  private void tearDownValues(){
    DomainClassName.executeUpdate('delete from DomainClassName') // Hibernate mapping will handle the table name for you
  }

  public void myTest() {
    //Test steps ...
    then:
    tearDownValues() //Call your tearDown method on the last step, after that and before cleanup(), auto rollback runs and you may have the same error as before
  }

Note that if you use @LoadDataSet you'll only need to call DomainClassName.executeUpdate('delete from DomainClassName') for the data you create inside your test. Spock will handle the rollback for everything @LoadDataSet creates.

Annotate test class with

@WebIntegrationTest
@Transactional

Annotate method with

@Rollback

Operate on DataSource wrapped by

org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
.newInstance(dataSource)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!