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

2024-05-07

我想在每个测试方法之前执行两个脚本,但我也想定义一些脚本在特定方法之前执行。使用 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() {
  
  }

}

运行这段代码only basic_data.sql被执行。如何解决这个问题呢?

我是否必须删除@Sql来自类的注释并为每个方法复制它/database/drop_schema.sql and /database/create_schema.sql定义?


UPDATE:这在即将推出的 Spring 框架中是可能的5.2通过新发布@SqlMergeMode注释(参见参考手册 https://docs.spring.io/spring/docs/5.2.0.RC1/spring-framework-reference/testing.html#spring-testing-annotation-sqlmergemode for 5.2.0.RC1).


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

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

这也记录在使用 @Sql 以声明方式执行 SQL 脚本 http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testcontext-executing-sql-declaratively参考手册的部分。

因此,不,遗憾的是不可能通过以下方式声明脚本@Sql在类级别执行如果@Sql也在方法级别定义。

如果您希望 Spring 支持此类组合,请创建 JIRA 问题 https://jira.spring.io/secure/CreateIssue!default.jspa请求此功能并选择Test 成分.

Thanks!

Sam (Spring TestContext 框架的作者)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐