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

流过昼夜 提交于 2021-02-20 13:31:12

问题


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?


回答1:


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)



来源:https://stackoverflow.com/questions/32871817/using-annotation-sql-is-it-possible-to-execute-scripts-in-class-level-before-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!