【发布时间】:2017-06-25 14:05:39
【问题描述】:
我知道这个论坛中还有一个问题可能看起来很相似。请在标记为重复之前通读。
我正在寻找一种方法来运行测试,该测试在另一个类中定义,它会通过 @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. 使用委托从 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,而不是任何其他解决方法。
【问题讨论】:
-
从
TestClass2显式调用setup()怎么样? -
因为 setup() 正在为 TestClass1 中的 @test 准备数据。从 TestClass2 调用时,此数据将超出 TestClass1 的范围。
-
TestClass1和TestClass2是同一类的子类吗?如果是这样,请考虑将@before注释移至其超类。 -
是的,它们是同一类的子类。我会试试的。
标签: java junit automation integration-testing