简体   繁体   English

用动态泛型类型测试Java泛型

[英]java testing generics with dynamic generic type

I'm writing junit3 tests. 我正在编写junit3测试。 I want to create a generic testing method ( assertIteratorThrowsNoSuchElement below) which can take my generic structure as 1st param and the generic type as 2nd param. 我想创建一个通用测试方法(下面的assertIteratorThrowsNoSuchElement ),可以将我的通用结构作为第一参数,并将通用类型作为第二参数。 That is because I want to check if the exception is thrown correctly once for string, then for integers and again for my own custom type. 那是因为我想检查一次是否为字符串正确抛出了异常,然后为整数正确抛出了异常,对于我自己的自定义类型再次抛出了异常。 This is the code I've got now: 这是我现在得到的代码:

public void testEmptyIteratorException () {
    Deque<String> deque = new Deque<String>();
    assertIteratorThrowsNoSuchElement(deque, String.class);
}

private void assertIteratorThrowsNoSuchElement(Deque<T> deque, Class<T> cl) {
    Iterator<T> iter = deque.iterator();
    try {
        iter.next();
        fail();
    } catch (NoSuchElementException expected) {
        assertTrue(true);
    }
}

The compiler dislikes: 编译器不喜欢:

The method assertIteratorThrowsNoSuchElement(Deque<T>, Class<T>) from the type DequeTest refers to the missing type T // the first method

Multiple markers at this line // the second method
- T cannot be resolved to a type
- T cannot be resolved to a type

My question is - what's the error in above code and how should it be done? 我的问题是-上面的代码有什么错误,应该怎么做?

You need to declare the type parameter for that method before using it. 您需要在使用之前声明该方法的类型参数。 To create a generic method, you declare the type parameter before the return type: 要创建泛型方法,请在返回类型之前声明type参数:

private <T> void assertIteratorThrowsNoSuchElement(Deque<T> deque, Class<T> cl) {
}

Also, I don't see any use of the 2 nd parameter there. 另外,我看不到第二个参数的任何使用。 You're not even using it. 您甚至都没有使用它。 The type parameter T is automatically inferred from the actual type you're passing. 类型参数T是根据您传递的实际类型自动推断出来的。 If you've added it for that purpose, then you can remove it. 如果为此目的添加了它,则可以将其删除。 Just keep the 1 st parameter. 只要保持在1 的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM