Search code examples
javagenericsjmock

Specify generic class type in argument matcher


Consider the following piece of code:

final Foo foo = context.mock(Foo.class);

context.checking(new Expectations() {{
    one(foo).someMethod(with(aNonNull(List.class)));
}});

I'm trying to suggest that someMethod is invoked with a non-null argument of type List<Bar>. However, I can't figure out the correct syntax to specify that the list contains objects of type Bar. The following simplistic attempt is not valid code:

final Foo foo = context.mock(Foo.class);

context.checking(new Expectations() {{
    one(foo).someMethod(with(aNonNull(List<Bar>.class)));
}});

Is there a correct way to do this or am I forced to add @SuppressWarnings("unchecked") to my test method?

I appreciate this is not strictly a JMock-specific question, but I thought I would tag it as such to attract those people who have possibly encountered this problem in the past.


Solution

  • Generics informations are erased at runtime [JB]Effective Java SE p.l14. So you have to check this an other way.

    I found this method to check the type of all element of the list :

    final Foo foo = context.mock(Foo.class);
    
    context.checking(new Expectations() {{
        oneOf(foo).someMethod((List<Object>) with(Every.everyItem(IsInstanceOf.instanceOf(Bar.class))));
    }});