java - 通用 JUnit 测试

标签 java generics junit

我有一个抽象的通用集合类 GCollection ,以及一个扩展名为 GStack 的类.

为了测试实现,我有一个抽象的 JUnit 测试类,我为每个 GCollection 扩展了它我做的实现:

public abstract class GCollectionTest<T extends GCollection<E>, E> {
    private GCollection<? extends Object> collection;
    protected abstract GCollection<T> createInstance();

    @Before
    public void setup() throws Exception {
        collection = createInstance();
    }

    // Tests down here. 

扩展如下:

public class GStackCollectionInterfaceTest<S extends GCollection<E>> {
    protected GDSStack<? extends Object> createInstance() {
        return new GDSStack<String>();
    }
}

我先用 GStack 测试控股String对象,然后使用 Date 重新运行测试对象以确保它适用于不同的对象类型。

@Test
public void testIsEmpty() {
    assertTrue(collection.isEmpty()); // Fresh Stack should hold no objects
    collection.add(new String("Foo")); // Error here.
    assertFalse(collection.isEmpty());
}

给出的错误是:

The method add(capture#24-of ? extends Object) in the type GCollection is not applicable for the arguments (String)

我对错误的理解是我不能把String对象变成 GCollection<T extends GCollection<E>>对象,但我不认为那是我想要做的。

我做错了什么?

如何在维护尽可能通用的测试的同时解决此错误?

最佳答案

集合类型为GCollection<? extends Object> .无法向此集合添加任何内容,请参阅:can't add value to the java collection with wildcard generic type .

子类中不需要通配符或边界,因此您可以简化泛型。像这样的东西:

abstract class GCollectionTest<T> {
    protected Collection<T> collection;

    protected abstract Collection<T> createCollection();
    protected abstract T createObject();

    @Before
    public void setup() throws Exception {
        collection = createCollection();
    }

    @Test
    public void testIsEmpty() {
        assertTrue(collection.isEmpty());
        collection.add(createObject());
        assertFalse(collection.isEmpty());
    }
}

class GStackCollectionInterfaceTest extends GCollectionTest<String> {
    protected GDSStack<String> createCollection() {
        return new GDSStack<String>();
    }

    protected String createObject() {
        return new String("123");
    }
}

由于泛型类型,允许在集合中使用不同类型,并由编译器检查,因此实际上不需要测试。我只想测试不同的容器类型,但您可以创建另一个使用 Date 的子类而不是 String .

关于java - 通用 JUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22493327/

相关文章:

java - 为什么我的后端应用程序未在Spring Boot中运行?

java - 谓词泛型方法

java - 如何在 Java 中传递函数时定义方法签名 - JUNIT with Hamcrest Fails

java - JUnit 5 测试未运行/检测到

java - 从另一个类调用 XMLUnit 测试

java - XML 的注解 @JsonDeserialize 的等价物

java - 为什么 java.time.ZoneOffset 实例排序为 'backwards' ?

Java - 使用泛型创建流畅的界面

c# - 为什么泛型类型参数中的隐式子到父转换是不可能的?

java - 将 myfeature.feature 作为 Cucumber JVM 测试运行时出现 JUNIT 错误 > potes.cucumberjvm.test.RunCucumberTest > 初始化错误