Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using annotation @Sql, is it possible to execute scripts in Class level before Method level?

I want to execute two scripts before every test method, but i also want to define some scripts to execute before specific methods. Using Spring framework and @Sql annotations, is it possible?

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/WEB-INF/application-context.xml")
@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD)
@Sql({ "/database/drop_schema.sql", "/database/create_schema.sql" })
public class CentralServiceTestCase {

  // I want to run "drop_schema.sql", "create_schema.sql" 
  // and "basic_data.sql" here
  @Test
  @Sql({ "/database/basic_data.sql" })       
  public void processActionWithSuccess() {

  }

  // I want to run only "drop_schema.sql" and "create_schema.sql" here
  @Test 
  public void anotherTestMethod() {

  }

}

Running this code only "basic_data.sql" is executed. How to solve this problem? I will have to remove @Sql anotation from class and replicate it for each method with "/database/drop_schema.sql" and "/database/create_schema.sql" defined?

like image 423
Sandro Simas Avatar asked Sep 30 '15 17:09

Sandro Simas


1 Answers

UPDATE: This is now possible in the upcoming Spring Framework 5.2 release via the new @SqlMergeMode annotation (see reference manual).


The 2nd paragraph of the Javadoc for @Sql explicitly states:

Method-level declarations override class-level declarations.

This is also documented in the Executing SQL scripts declaratively with @Sql section of the reference manual.

Thus, no, it is unfortunately not possible to have scripts declared via @Sql at the class level be executed if @Sql is also defined at the method level.

If you would like for Spring to support such combinations, please create a JIRA issue requesting this feature and select the Test Component.

Thanks!

Sam (author of the Spring TestContext Framework)

like image 177
Sam Brannen Avatar answered Sep 24 '22 00:09

Sam Brannen