testing - 通用 JUnit 测试类

标签 testing junit

我写了一个接口(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/

相关文章:

java - Selenium 和 xpath : finding a div with a class/id and verifying text inside

http - 如何测试http JSON服务器的性能?

testing - 断言失败。无法确定原因?

java - 如何将 Class<?> 与 Hamcrest Matcher 中的特定 Class 实例进行匹配?

file-io - Groovy:无法将类 'true' 的对象 'java.lang.Boolean' 转换为类 'java.io.File'

testing - 这个 fatal error 从何而来? cakephp phpunit

java - 输出流持久化问题

java - EasyMock 当我们在测试类上调用 db 时

java - 对象列表上的 JUnit Mockito ReflectionEquals

go - 是否可以更改 os.Args 的值以便我可以将测试添加到我正在创建的 CLI 中?