【问题标题】:Multiple runwith for a junit test class一个junit测试类的多个runwith
【发布时间】:2015-01-27 14:18:48
【问题描述】:

有谁知道如何解决这个问题。

@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(Parametrized.class)

@ContextConfiguration("/META-INF/blah-spring-test.xml")
public class BlahTest
..

所以我想进行弹簧性质测试,同时希望对其进行参数化以避免代码重复...

【问题讨论】:

标签: spring junit annotations


【解决方案1】:

您不能像评论帖子中指出的那样使用两个跑步者。您应该使用 Parameterized 运行器作为使用 Spring 的 TestContextManager 来加载 Spring 上下文。

@Before 
public void before() throws Exception {
  new TestContextManager(getClass()).prepareTestInstance(this);
}

【讨论】:

    【解决方案2】:

    从 Spring Framework 4.2 开始,基于 JUnit 的集成测试现在可以使用 JUnit 规则而不是 SpringJUnit4ClassRunner 来执行。这允许基于 Spring 的集成测试与 JUnit 的 Parameterized 等替代运行程序或 MockitoJUnitRunner 等第三方运行程序一起运行。在spring doc 上查看更多详细信息。

    【讨论】:

      【解决方案3】:

      John B's answer 的基础上使用TestContextManager,还可以调用beforeTestMethod()afterTestMethod() 以更好地模拟SpringJUnit4ClassRunner 的行为(例如使用@Sql 加载数据库)。

      这些方法需要一个Method 参数,因此可以利用JUnit4 的TestName 规则来获取当前测试方法的名称,然后通过反射检索它。

      private static TestContextManager springTestContext
        = new TestContextManager(BlahTest.class);
      
      @Rule
      public TestName testName = new TestName();
      
      @Before
      public void before() throws Exception {
        springTestContext.prepareTestInstance(this);
        springTestContext.beforeTestMethod(this,
          getClass().getMethod(testName.getMethodName()));
      }
      
      @After
      public void after() throws Exception {
        springTestContext.afterTestMethod(this,
          getClass().getMethod(testName.getMethodName()), null);
      }
      

      【讨论】:

        猜你喜欢
        • 2015-07-26
        • 2011-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多