mockito:如何在方法调用中返回mocked类对象

c9qzyr3d  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(249)

我想为下面的类编写单元测试。这个班只有 execute 方法,它需要3个参数,所以我可以为这些参数提供mock/fakes。然而,它也 SiteInfo.filter 调用inside方法,所以我也应该模拟这个对象。
我有一个错误:
org.mockito.exceptions.misusing.unfinishedstubbingexception:此处检测到未完成的存根:

public static class SiteResponseExecutor
{
  public SiteResourseExecute execute(final String url,
                                     final SiteResponse response,
                                     final Map<String, String> responseData)
  {
    final String responseType = responseData.get(type);
    final SiteInfo siteInfo = SiteInfo.filter(responseType);

    if (siteInfo.getType() != null)
    {
      ....

      if (siteInfo.getEncode() != null && siteInfo.getType().startsWith("image"))
      {
        ...
      }
    }
    else if (responseData.get(HttpClient.HEADER_CONTENT_LENGTH) != null)
    {
      ...
    }

    return new SiteResourseExecute(
        siteInfo.getType(), siteInfo.getEncode(),
        response.getResponseStatus(), getPharese(response.getStatus()),
        responseData, response.getInputStream());
  }
}
``` `filter` 是

public static SiteInfo filter(final String type)
{
final SiteInfo siteInfo = new SiteInfo();

...
return siteInfo;
}

当我试图嘲笑 `execute` 方法前两个方法返回原语,但最后一个返回类示例,所以我想让它返回已经模拟的对象。

// creating mock object to pass it when filter() method is called
final SiteInfo mockSiteInfo = Mockito.mock(SiteInfo.class);
mockSiteInfo.setType("application/octet-stream");
mockSiteInfo.setEncoding("gzip, deflate");

// first two when are OK, but the last one gives UnfinishedStubbingException
final SiteInfo siteInfo = Mockito.mock(SiteInfo.class);
Mockito.when(siteInfo.getType()).thenReturn("type1");
Mockito.when(siteInfo.getEncode()).thenReturn("type2");
doReturn(mockSiteInfo).when(SiteInfo).filter("type1");

如何返回此方法调用的模拟对象?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题