我有一个抽象的泛型集合类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());
}给出的错误是:
方法添加(捕获#24-of?GCollection类型中的扩展对象)不适用于参数(字符串)
我对错误的理解是,我不能将String对象放入GCollection<T extends GCollection<E>>对象,但我认为这不是我想要做的。
我做错了什么?
如何在维护尽可能通用的测试的同时解决此错误?
发布于 2014-03-19 00:56:18
集合的类型是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的子类。
https://stackoverflow.com/questions/22493327
复制相似问题