7

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?

Do I will have to remove the @Sql anotation from class and replicate it for each method with /database/drop_schema.sql and /database/create_schema.sql defined?

Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
Sandro Simas
  • 1,268
  • 3
  • 21
  • 35

1 Answers1

8

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


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)

Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
Sam Brannen
  • 29,611
  • 5
  • 104
  • 136
  • 1
    Or [SPR-16021](https://jira.spring.io/browse/SPR-16021). It would be really nice feature. – kqr Dec 20 '17 at 16:13
  • 2
    This is now possible in the upcoming Spring Framework 5.2 release via the new `@SqlMergeMode` annotation. See update in answer. – Sam Brannen Aug 28 '19 at 11:20