首页 > 解决方案 > 如何使用 mockito 框架获取返回的对象

问题描述

Mockito 框架的新手。

 RcExtensionInfo rcExtensionInfo = rcApiClient.get(
                RC_OFFICE_EXTENSION_INFO_API_PATH,
                pathVariablesForExtensionInfoRequest,
                customRequestHeaders,
                RcApplicationHeadersService.RcApplicationType.OFFICE_INTEGRATION,
                RcExtensionInfo.class
        );

上面的代码我需要用 mockito 测试,我想要真正的对象,RcExtensionInfo因为这个对象在我的代码中用于少数 getter 方法。目前无法调用 getter 方法,因为null. 我们知道,如果我们模拟某个方法,那么默认值就是null. 但我认为我们可以将thenReturn方法中的对象分配给该引用。

测试代码:

RcAccountInfo rcAccountInfo = new RcAccountInfo();
    rcAccountInfo.setMainNumber("+198473621");
    when(rcApiClient.get(RC_OFFICE_ACCOUNT_INFO_API_PATH,
            new HashMap<String, String>(), new HashMap<String, String>(),
            RcApplicationHeadersService.RcApplicationType.OFFICE_INTEGRATION,
            RcAccountInfo.class)).thenReturn(rcAccountInfo);

标签: javamockitojunit5

解决方案


您可以调用Mockito.mock(YourClass.class, Mockito.CALLS_REAL_METHODS)它,如果 没有配置任何其他内容when(..).then(...),则在模拟对象上调用真正的方法。


推荐阅读