【问题标题】:Mocking class object having setter getter methods present in function using mockito使用 mockito 在函数中模拟具有 setter getter 方法的类对象
【发布时间】:2016-04-21 12:10:29
【问题描述】:

我有一个要求,我需要从 web 服务中获得一些响应。需要模拟函数 getPdf。我无法模拟 GetDocumentRequestGetDocumentResponse。 我需要用于模拟的 Mockito 或 PowerMockito。 例如:

Class xyz {
    // mocking required.
    String getPdf (int I, String h){
        return  getDoc(I, h):
     }

    String getDoc (int I, String h){
        GetDocumentRequest d = factory.getDocument ():
        d.setversion (I);
        d.setname (h):
        GetDocumentResponse r  = getService ().getPdfDoc (d):
        // webservice
        return r.getPdfString ();
   }


}

【问题讨论】:

  • 不清楚你在问什么。如果需要模拟getPdfDoc();那么显然你必须实际模拟你对getService() 的调用将返回的对象。您的代码并没有告诉我们getService() 实际在做什么。旁注:避免所有在其名称中带有“权力”的模拟框架。它们带来的麻烦多于好处。
  • 使用 spock。这将减少对您的代码的干扰,并使您的测试更整洁。
  • 我需要模拟 getPdf(),然后调用 getDoc()。我无法模拟 getdocumentRequest 和 GetDocumentResponse 对象

标签: java spring mockito powermockito


【解决方案1】:

Mockito 应该足以模拟普通方法。 也许类似的东西?

@Test
public void test() {
   Xyz xyz = mock(Xyz.class);
   when(xyz.getPdf(any(Integer.class), any(String.class)).thenReturn("this is my pdf");
}

【讨论】:

  • 但是 GetDocumentRequest 和 GetDocumentResponse 并没有被嘲笑,因此返回 null
  • 好的。然后我不太明白我必须承认的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-07
  • 2012-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多