@SQL one time per class

♀尐吖头ヾ 提交于 2019-12-23 12:49:34

问题


I'm writing some integration test using spring framework. I have different SQL scripts for different integration test classes. Something like this:

@ContextConfiguration(classes = ...)
@Sql("classpath:sportCenter-test.sql")
public class SportCenterResourceIT {
    ...
}

Everything works perfectly except for the fact that the SQL script is executed before each test, instead of one time per class. I have already searched for some time the spring documentation but I was not able to find something related to such an option.

Could anybody give me an hint?


回答1:


Adding the org.springframework.transaction.annotation.Transactional annotation at the class level will prevent any changes from @Sql scripts from persisting between tests. So your code becomes:

@ContextConfiguration(classes = ...)
@Sql("classpath:sportCenter-test.sql")
@Transactional
public class SportCenterResourceIT {
    ...
}

This combination will result in the following:

  1. Your @Sql script will run before each test
  2. The test itself will run
  3. Any database changes from steps 1 or 2 will be reverted at the end of each test



回答2:


I use this way to resolve the problem:

@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
@Sql("classpath:sql/DataForRouteTesting.sql")
public class MyTest {}

Scripts are executed every time, but there are not conflict primary key.




回答3:


I solved my problem by putting the sql script in the src/test/resources folder with the name data.sql. This file is executed once at startup of each integration test. For this to work, you need to remove the @Sql annotation.



来源:https://stackoverflow.com/questions/29153100/sql-one-time-per-class

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