Mocking generic interfaces

2,766 views
Skip to first unread message

Erik Ramfelt

unread,
Jul 30, 2009, 4:28:33 AM7/30/09
to moc...@googlegroups.com
Hi everyone

I have the following interface that I would like to mock when testing a class.

public interface Evaluator<T extends Action>
{
public abstract double evaluate(List<T> actionSequence);
}

Is it possible to create a mock that has a generic type of Action? ie
I want the mock objet to have the generic type ChildAction. I would
like to have something like this, but this will throw a
"java.lang.ClassCastException: java.lang.Class cannot be cast to
java.lang.reflect.ParameterizedType".

Evaluator<ChildAction> evaluator = Mockito.mock(Evaluator.class);

Also the class under test will use reflection of the object
implementing the Evaluator interface to find the generic type so it
can create a Class<T> of it as it needs to be fed into an API. I used
reflection so I didnt have to have a "Class<T> getClass()" method in
the interface.

But I guess that will not play nice with the mockito logic as the
mocked object is not a real implementation of the Evaluator interface?

public class ActionBasedSequenceRule
{
public static Class<? extends Action> getActionClass(Evaluator<?
extends Action> evaluator)
{
....
Type t =
evaluator.getClass().getGenericInterfaces()[0].getActualTypeArguments()[0];
....
}
}


So what do you think, is this even remotly possible or just a dumb idea?

Regards
//Erik

szczepiq

unread,
Jul 31, 2009, 12:58:22 PM7/31/09
to moc...@googlegroups.com
> public interface Evaluator<T extends Action>
> {
> public abstract double evaluate(List<T> actionSequence);
> }
>
> Is it possible to create a mock that has a generic type of Action? ie
> I want the mock objet to have the generic type ChildAction. I would
> like to have something like this, but this will throw a
> "java.lang.ClassCastException: java.lang.Class cannot be cast to
> java.lang.reflect.ParameterizedType".
>
> Evaluator<ChildAction> evaluator = Mockito.mock(Evaluator.class);

Above should work just fine, just suppress the warning ;)

Given the above code works what's the problem?

Cheers,
Szczepan Faber
Reply all
Reply to author
Forward
0 new messages