如何将多个Spring测试注释组合成一个注释?

10

我正在使用Spring Boot在我的测试类上方便地添加注释,进行集成测试。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Config.class)
@IntegrationTest
@Sql({"classpath:rollback.sql", "classpath:create-tables.sql"})
@Transactional

我觉得在每个测试类中复制/粘贴整个代码块很难看,因此我创建了自己的@MyIntegrationTest注释。

@SpringApplicationConfiguration(classes = Config.class)
@IntegrationTest
@Sql({"classpath:database-scripts/rollback.sql", "classpath:database-scripts/create-tables.sql", "classpath:database-scripts/insert-test-data.sql"})
@Transactional
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyIntegrationTest {
}

然而,如果我在我的新注解中添加@RunWith(SpringJUnit4ClassRunner.class),那么JUnit会运行其默认的运行器-这是不可取的。 因此,现在我必须使用两个注解。

@RunWith(SpringJUnit4ClassRunner.class)
@MyIntegrationTest

我想现在这样也可以,但有没有一种方法可以合并这些注释,这样我就能使用一个注释了呢?


1
我猜这就是你能得到的最好的了... http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html#integration-testing-annotations-meta - sodik
好的,我已经深入研究了JUnit代码。 AnnotatedBuilder 类是尝试通过注释检测任何Runner的类,并且它们使用:RunWith annotation = currentTestClass.getAnnotation(RunWith.class);,因此它不会获取“注释上的注释”。虽然不确定为什么没有实现它,但我将在他们的GitHub上询问。 - Guillaume
2个回答

8

元注解不是代码重用的唯一方式。我们使用继承来实现:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Config.class)
@IntegrationTest
@Sql({"classpath:rollback.sql", "classpath:create-tables.sql"})
@Transactional
public abstract class IntegrationTest {
}

public class FooTest extends IntegrationTest {

}

public class BarTest extends IntegrationTest {

}

与元注释不同,Spring和JUnit都可以理解从基类继承的注释。

对我来说,这是一个正确的答案,即使我希望拥有除了继承之外的其他东西。当代码库增长时,继承总会带来一些耦合问题,而且以后很难摆脱抽象类,但我想现在这是我能得到的最好的东西。 - Guillaume
不幸的是,这对我没有用。当我只将我的@RunWith(SpringRunner.class)注解添加到抽象类时,应用程序上下文不再加载。 - Michael Lihs
为了完整起见,这里有一篇博客文章反对在测试中使用继承:https://www.petrikainulainen.net/programming/unit-testing/3-reasons-why-we-should-not-use-inheritance-in-our-tests/ 主要的论点是:
  1. 继承不是重用代码的正确工具
  2. 继承可能会对我们的测试套件的性能产生负面影响
  3. 使用继承会使测试更难阅读
- ZeroOne

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接