【问题标题】:How to get returned object using mockito framework如何使用 mockito 框架获取返回的对象
【发布时间】:2019-11-01 12:49:26
【问题描述】:

Mockito 框架的新手。

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

上面的代码我需要用 mockito 测试,我想要RcExtensionInfo 的真实对象,因为这个对象在我的代码中用于少数 getter 方法。由于null,目前无法调用getter 方法。据我们所知 如果我们模拟一些方法,那么默认值将是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);

【问题讨论】:

    标签: java mockito junit5


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您的第四个when 中的问题是您使用的对象将在您的测试中成为另一个对象。因为测试中的whennew HashMap&lt;String, String&gt;() 中的new HashMap&lt;String, String&gt;() 不是等于对象。所以你的when 永远不会打电话。你应该使用这样的东西:

      when(rcApiClient.get(RC_OFFICE_ACCOUNT_INFO_API_PATH,
              Mockito.anyMap(), Mockito.anyMap(),
              RcApplicationHeadersService.RcApplicationType.OFFICE_INTEGRATION,
              RcAccountInfo.class)).thenReturn(rcAccountInfo);
      

      【讨论】:

      • 如果你使用ArgumentMatcher(比如anyMap()),Mockito 要求所有参数都是ArgumentMatchers,所以你需要使用eq() 作为类型和类参数。跨度>
      猜你喜欢
      • 2019-09-18
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多