2

This is a really newbie question but I don't know how to stub this.

I have to mock a method to return Class like this.

public Class<? extends SomeClass> getAClass();

if I do something like this

when(this.someInstance.getAClass())
    .thenReturn(SomeClassThatExtendsSomeClass.class);

I get compilation error.

The method thenReturn(Class<capture#1-of ? extends SomeClass>) in the type OngoingStubbing<Class<capture#1-of ? extends SomeClass>> is not applicable for the arguments (Class<SomeClassThatExtendsSomeClass>)
Don Roby
  • 40,677
  • 6
  • 91
  • 113
toy
  • 11,711
  • 24
  • 93
  • 176

3 Answers3

5

If the method declaration can be changed to what @Bohemian suggested above,

public <T extends SomeClass> Class<T> getAClass();

then you can write your mock statement as follows:

when(this.someInstance.<SomeClassThatExtendsSomeClass>getAClass())
     .thenReturn(SomeClassThatExtendsSomeClass.class);

Otherwise, the doReturn semantics should be used as follows:

Mockito
    .doReturn(SomeClassThatExtendsSomeClass.class)
    .when(this.someInstance.<SomeClassThatExtendsSomeClass>getAClass());
Vikdor
  • 23,934
  • 10
  • 61
  • 84
  • What if I can't change the method declaration? – toy Nov 12 '12 at 12:07
  • Then you should use the less type-safe `doReturn()` semantics to escape the compiler error while using `when().thenReturn()` semantics. – Vikdor Nov 12 '12 at 12:18
2

If you can't change the method declaration so that it will work with thenReturn then you could use thenAnswer:

when(this.someInstance.getAClass()).thenAnswer(new Answer<Class<? extends SomeClass>>() {
            @Override
            public Class<? extends SomeClass> answer(InvocationOnMock invocation) throws Throwable {
                return SomeClassThatExtendsSomeClass.class;
            }
});

While it isn't ideal to do an implementation of Answer just to return a fixed value this should work for your scenario.

mikej
  • 65,295
  • 17
  • 152
  • 131
0

Try typing the method:

public <T extends SomeClass> Class<T> getAClass();

when(this.someInstance.getAClass())
    .thenReturn(SomeClassThatExtendsSomeClass.class);
Bohemian
  • 412,405
  • 93
  • 575
  • 722