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?

1 Answer 1

7

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Or SPR-16021. It would be really nice feature.
This is now possible in the upcoming Spring Framework 5.2 release via the new @SqlMergeMode annotation. See update in answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.