我写了一个接口(interface)MyInterface
,它将被不同的实现者实现。
我还编写了一个类 MyInterfaceTest
,其中包含所有实现者都应该能够用来测试其实现的通用测试方法。
我只是不知道如何让它作为 JUnit 测试工作。
目前,我有这样的东西:
public class MyInterfaceTest {
private static MyInterface theImplementationToTest = null;
@BeforeClass public static void setUpBeforeClass() throws Exception {
// put your implementation here:
theImplementationToTest = new Implementation(...);
}
@AfterClass public static void tearDownAfterClass() throws Exception {
theImplementationToTest = null;
}
@Test public void test1() { /* uses theImplementationToTest */ }
@Test public void test2() { /* uses theImplementationToTest */ }
}
我使用静态方法setUpBeforeClass
,因为每个实现的初始化都需要很多时间,所以我想对所有测试都初始化一次。
对于这个版本的测试,实现者必须更改 setUpBeforeClass
的代码并放置他们自己的实现。
我确信还有另一种方法可以编写MyInterfaceTest
,这样实现者只需继承它或向它发送一个参数,而不需要更改代码。但是,我在 JUnit 方面经验不足,无法使其正常工作。你能告诉我怎么做吗?
最佳答案
您可以让子类只实现前类方法并继承所有测试。
import org.junit.*;
public class ImplementingClassTest extends MyInterfaceTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
// put your implementation here:
theImplementationToTest = new MyInterfaceImpl();
}
}
这使得您正在编写的抽象类看起来像:
import org.junit.*;
public abstract class MyInterfaceTest {
protected static MyInterface theImplementationToTest = null;
@AfterClass
public static void tearDownAfterClass() throws Exception {
theImplementationToTest = null;
}
@Test
public void test1() { /* uses theImplementationToTest */
}
@Test
public void test2() { /* uses theImplementationToTest */
}
}
通常,您会将方法作为实现抽象所需的子类。不能在这里这样做,因为它是一种静态设置方法。 (此外,您可能希望重构实例化,以免花费很长时间,因为这通常是一种反模式)。
关于testing - 通用 JUnit 测试类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11604288/