Reputation: 869
I have a class LoggerInterceptor with an InvocationContext as parameter. For this class I am trying to write a unit test but I am stuck on the first line:
public class LoggerInterceptor{
public method log(InvocationContext context) {
String name = invocationContext.getTarget().getClass().getName();
.....
}
My test looks like this:
@Test
public void logTest() throws Exception {
LoggerInterceptor objectToTest = new LoggerInterceptor();
InvocationContext context = Mockito.mock(InvocationContext.class);
Object target = Mockito.mock(Object.class);
Mockito.when(context.getTarget()).thenReturn(target);
MockGateway.MOCK_GET_CLASS_METHOD = true;
Mockito.doReturn(objectToTest.getClass()).when(target).getClass();
MockGateway.MOCK_GET_CLASS_METHOD = false;
objectToTest.log(context);
}
I am getting a UnfinishedStubbingException when I call the method log(context).
If I try with:
Mockito.when(target.getClass()).thenReturn(objectToTest.getClass());
I get this exception:
The method thenReturn(Class<capture#3-of ? extends Object>) in the type OngoingStubbing<Class<capture#3-of ? extends Object>> is not applicable for the arguments (Class<capture#4-of ? extends LoggerInterceptor>)
Is there any way I can pass this first line? The String that I get back is not important.
Upvotes: 0
Views: 944
Reputation: 95654
Object.getClass() is final. Final methods can't be mocked or stubbed with Mockito, because the compiler sees "final", skips the virtual method dispatch, and consequently Mockito can neither intercept calls to the method nor identify the method in doReturn
, when
, or verify
. When you interact with Mockito later, it detects that you started stubbing but cannot detect that you finished, so it throws an UnfinishedStubbingException.
If you want to have target
adjust the type or types it appears as, you'll need to change the class object passed into Mockito.mock
, or add withSettings().extraInterfaces(...)
.
Upvotes: 3