testing – Generic JUnit测试类

前端之家收集整理的这篇文章主要介绍了testing – Generic JUnit测试类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我编写了一个接口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 */
    }
}

通常,您将使该方法成为实现抽象所需的子类.这里不能这样做,因为它是静态设置方法. (此外,您可能希望重构实例化不需要很长时间,因为这通常是反模式).

原文链接:https://www.f2er.com/java/129785.html

猜你在找的Java相关文章