Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@SQL one time per class

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?

like image 441
Mihai238 Avatar asked Mar 19 '15 19:03

Mihai238


2 Answers

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
like image 191
mskluev Avatar answered Oct 21 '22 18:10

mskluev


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.

like image 39
tatka Avatar answered Oct 21 '22 17:10

tatka