| Author |
Testing several implementations of generic interface
|
Istvan Kovacs
Ranch Hand
Joined: May 06, 2010
Posts: 100
|
|
Dear All,
I'd like to write a unit test for classes implementing the same generic interface, Something<T> - the classes are solutions to the same puzzle from different students, and I don't want to influence the types they use for data storage, or the algorithm they use to generate the result, as long as the implementation passes the tests. Each class implements Something<T> with a specific class, e.g.
Then, I'd like to have a test where I only need to change the line that instantiates the object (Something<T> implementation) under test. I've come up with:
I don't want to create a whole parallel tree of ThingTest<Integer>, ThingTest<String>; this would be used to test each class just one, to verify puzzle solutions from students (the aim is to let them use whatever data structure they choose or create, that's why I'd like to keep this generic). To check each solution, I'd just replace new IntegerThing() with whatever class they used.
Now, this works fine, but gives me a warning: unchecked cast from IntegerThing to Something<T>[u]. Is there a way to avoid this? At compile time, it is known that [u]IntegerThing implements Something<Integer>; is there a way to get the compiler figure out that T is Integer in this case?
Thanks,
Kofa
|
 |
Ireneusz Kordal
Ranch Hand
Joined: Jun 21, 2008
Posts: 423
|
|
Istvan Kovacs wrote:
Now, this works fine, but gives me a warning: unchecked cast from IntegerThing to Something<T>[u]. Is there a way to avoid this? At compile time, it is known that [u]IntegerThing implements Something<Integer>; is there a way to get the compiler figure out that T is Integer in this case?
Use @SuppressWarnings("unchecked") annotation.
|
 |
Istvan Kovacs
Ranch Hand
Joined: May 06, 2010
Posts: 100
|
|
Use @SuppressWarnings("unchecked") annotation
:-)
I know how I can suppress the warning, but that would be my last resort (I know that even some of the code in Java Generics and Collections, which is a great book on the subject, has some warnings that cannot be avoided).
My main concern is that the type parameter on ThingTest<T> does not really belong there. I never instantiate ThingTest<This> or ThingTest<That>; it's always done by the JUnit framework that does not care about generics.
|
 |
Istvan Kovacs
Ranch Hand
Joined: May 06, 2010
Posts: 100
|
|
Here's the solution. It works because Something<?> undertest means "the Something interface parameterised with an unknown, but concrete type"; then, it doTest, T captures the wildcard, and becomes that "unknown, but concrete type".
|
 |
 |
|
|
subject: Testing several implementations of generic interface
|
|
|