我知道这个论坛中还有另一个问题可能看起来很相似。请在标记为重复之前通读。
我正在寻找一种运行测试的方法,该测试在另一个类中定义,以某种方式通过@before 注释。
public TestClass1 {
@before
public void setup() throws Exception{
super.setup();
}
@Test
public void testSomething(){...}
}
public TestClass2 {
@Test
public void testSomethingAndSomethingElse() {
// Somehow execute testSomething() in a way which will force
it to go through the @before
// and then test something else
}
}
在类似的在线问题中,有 2 个建议:
1. 从 TestClass1 扩展 TestClass2 - 这对我来说是不可能的,因为我已经扩展了另一个类。
2. 使用委托(delegate)从 TestClass2 访问 TestClass1,如下所示:
// Instantiate TestClass1 as a member of TestClass2
public TestClass2 {
private TestClass1 one = new TestClass1();
public void testSomethingAndSomethingElse1() {
one.testSomething();
}
}
这里的问题是,当调用 one.testSomething() 时,您将不会通过 TestClass1 的 @before 注释,在我的例子中,这是初始化其他对象所必需的。
还有别的办法吗?
用于集成测试而不是单元测试。 我需要能够在另一个 @test 中使用 @test,而不是任何其他解决方法。
最佳答案
如果您尝试在多个测试类中重用相同的代码,我建议使用 JUnit
框架中的 @Rule
。也许ExternalResource
是你需要的:
public class SetupResource extends ExternalResource {
@Override
protected void before() throws Throwable {
//setup the code
}
}
将你想要的代码放在before()
方法中,然后像这样定义JUnit
Rule
:
@Rule
public ExternalResource resource = new SetupResource ()
关于java - 如何在另一个测试类中使用现有的 JUnit 测试,使其通过@before?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44747146/