【问题标题】:Is there a workaround for using @RunWith in JUnit?在 JUnit 中使用 @RunWith 是否有解决方法?
【发布时间】:2014-04-03 09:00:11
【问题描述】:

我有一个主要的测试类 (A) 和另一个从它扩展的 (B)。

A 有一个 @RunWith(SpringJUnit4ClassRunner.class) 注释来初始化它。 我需要在 B 上使用@RunWith(JUnitParamsRunner.class) 注释。

但我似乎无法同时做到这两点。有没有办法在没有@RunWith 注释的情况下使用参数化测试套件?

另一种解决方案是使用

testContextManager = new TestContextManager(AbstractInvoiceCreationModuleTest.class);
testContextManager.prepareTestInstance(this);

但是我不能在@BeforeClass 方法中写这个,因为它是静态的并且不允许使用它。我不希望在@Before 方法中编写上述代码,因为该类将在每个测试方法之前被初始化。并且很多测试类都从 A 扩展而来。

可以做什么?

【问题讨论】:

    标签: java spring unit-testing junit


    【解决方案1】:

    Spring 在 4.2 版中添加了对基于 @Rule 的 JUnit 对 Spring 上下文的支持。

    http://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/integration-testing.html#testcontext-junit4-rules

    该文档中的示例:

    // Optionally specify a non-Spring Runner via @RunWith(...)
    @ContextConfiguration
    public class IntegrationTest {
    
       @ClassRule
       public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
    
       @Rule
       public final SpringMethodRule springMethodRule = new SpringMethodRule();
    
       @Test
       public void testMethod() {
          // execute test logic...
       }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用规则代替SpringJUnit4ClassRunner.class:http://www.alexecollins.com/tutorial-junit-rule/

      【讨论】:

      • 这个链接很有用,谢谢!
      • 只是我的 2c,在每个测试方法之前初始化 Spring 应用程序上下文(如博客文章中所示)不是很有效,并且会显着降低测试的性能。测试上下文应该被缓存(不知何故)。例如。 spring-test 框架只初始化一次上下文,它被所有测试共享。
      【解决方案3】:

      我不知道那个具体案例(Spring 测试运行器),但我有一个类似的案例并最终创建了自己的运行器。

      【讨论】:

      • 我不想写跑步者。这违背了使用参数化测试的目的,我将不得不编写逻辑,这可能会引入错误。
      • 我建议将 SpringJunit4ClassRunner 扩展到 SpringJunit4ParamRunner (或反向)。您显然不想创建具有特定于您的测试的逻辑的运行器。虽然它们写起来很痛苦,所以只有当你有许多具有相同模式的测试时才值得。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-07
      • 1970-01-01
      • 2021-12-30
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      相关资源
      最近更新 更多