我有一个抽象的通用集合类 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/