Mockito UnfinishedStubbingException试图模拟获取类

时间:2015-01-12 14:55:23

标签: java unit-testing mockito

我有一个LoggerInterceptor类,其中InvocationContext作为参数。 对于本课程,我正在尝试编写一个单元测试,但我被困在第一行:

public class LoggerInterceptor{
  public method log(InvocationContext context) {
    String name = invocationContext.getTarget().getClass().getName();
    .....
  }

我的测试看起来像这样:

@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);
}

当我调用方法log(context)时,我收到一个UnfinishedStubbingException。

如果我尝试:

Mockito.when(target.getClass()).thenReturn(objectToTest.getClass());

我得到了这个例外:

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>) 

有什么方法可以通过这第一行吗?我得到的字符串并不重要。

1 个答案:

答案 0 :(得分:3)

Object.getClass()是最终的。最终方法不能用Mockito模拟或存根,因为编译器看到“final”,跳过虚拟方法调度,因此Mockito既不能拦截对方法的调用,也不能识别doReturn中的方法,{{1 },或when。当您稍后与Mockito交互时,它会检测到您开始存根但无法检测到您已完成,因此会抛出UnfinishedStubbingException。

如果您希望verify调整其显示的类型,则需要更改传递到target的类对象,或添加Mockito.mock

相关问题