testing – Generic JUnit测试类
发布时间:2020-05-30 08:45:55 所属栏目:Java 来源:互联网
导读:我编写了一个接口MyInterface,它将由不同的实现者实现. 我还编写了一个MyInterfaceTest类,它包含所有实现者应该能够用来测试其实现的通用测试方法. 我只是不知道如何让它作为JUnit测试工作. 目前,我有这样的事情: public class MyInterfaceTest { private st
|
我编写了一个接口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 */
}
}
通常,您将使该方法成为实现抽象所需的子类.这里不能这样做,因为它是静态设置方法. (此外,您可能希望重构实例化不需要很长时间,因为这通常是反模式). (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
