简体   繁体   中英

java testing generics with dynamic generic type

I'm writing junit3 tests. 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. 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:

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. If you've added it for that purpose, then you can remove it. Just keep the 1 st parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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