一个JUnit测试类中的多个runwith是什么意思?

7

有人知道如何解决这个问题吗?

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

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

我希望进行一个Spring自然测试,同时希望将其参数化以避免代码重复...


4
重复:https://dev59.com/w2Af5IYBdhLWcg3woz9n。 - Ilya Ovesnov
3
我建议这并不完全是重复的,因为跑步者是不同的。 - John B
3个回答

4

如评论帖子中所述,您不能使用两个运行程序。您应该使用Parameterized运行程序,并使用Spring的TestContextManager来加载Spring上下文。

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

0
自从Spring Framework 4.2版本以来,基于JUnit的集成测试现在可以使用JUnit规则(JUnit rules)来执行,而不是使用SpringJUnit4ClassRunner。这样就可以使用其他的运行器,如JUnit的Parameterized或第三方运行器,如MockitoJUnitRunner来运行基于Spring的集成测试。更多详情请参见spring doc

0

John B的答案的基础上,使用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);
}

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