使用注释@Sql,是否可以在方法级别之前执行类级别的脚本?

时间:2015-09-30 17:01:15

标签: spring spring-test

我想在每个测试方法之前执行两个脚本,但我还想在特定方法之前定义一些要执行的脚本。使用Spring框架和 @Sql 注释,是否可能?

@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() {

  }

}

仅运行此代码" basic_data.sql" 将被执行。如何解决这个问题呢?我将不得不从类中删除@Sql anotation并使用" /database/drop_schema.sql" " / database / create_schema为每个方法复制它。 sql" 定义了什么?

1 个答案:

答案 0 :(得分:4)

更新:这可能会在SPR-14357中得到解决。

@Sql的Javadoc第2段明确指出:

  

方法级声明会覆盖类级声明。

参考手册的Executing SQL scripts declaratively with @Sql部分也记录了这一点。

因此,不幸的是,如果在方法级别定义了@Sql,则不可能在类级别通过@Sql声明脚本。

如果您希望Spring支持此类组合,请create a JIRA issue申请此功能并选择Test 组件

谢谢!

Sam( Spring TestContext Framework的作者