问题
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:
- Your
@Sql
script will run before each test - The test itself will run
- 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