当前位置: 首页 > 知识库问答 >
问题:

mockito-需要但没有调用:实际上,与这个mock没有任何交互

霍修筠
2023-03-14
void setEyelet(final PdfWriter printPdf, final float posX, final float posY) {

    InputStream is = WithDefinitions.class.getResourceAsStream(RES_EYELET); //RES_EYELET is a pdf.
    PdfContentByte canvas = printPdf.getDirectContent();

    PdfReader reader = new PdfReader(is);
    PdfImportedPage page = printPdf.getImportedPage(reader, 1);
    canvas.addTemplate(page, posX, posY);
    reader.close();
}
canvas.addTemplate(page, posX, posY); 
void computeEyelets(final PdfWriter printPdf) {
        float lineLeft = borderLeft + EYELET_MARGIN;
        float lineRight = printPdfWidth - borderRight - EYELET_MARGIN - EYELET_SIZE;
        float lineTop = printPdfHeight - borderTop - EYELET_MARGIN - EYELET_SIZE;
        float lineBottom = borderBottom + EYELET_MARGIN;
        float eyeletDistMinH = 20;
        if (eyeletDistMinH != 0 || eyeletDistMinV != 0) {
         setEyelet(printPdf, lineLeft, lineBottom);
    }
public void computeEyeletsNoMirror() {
    PdfWriter pdfWriter = Mockito.mock(PdfWriter.class);
    PdfContentByte pdfContentByte = Mockito.mock(PdfContentByte.class);
    Mockito.when(pdfWriter.getDirectContent()).thenReturn(pdfContentByte);
    WithDefinitions withDefinitions = Mockito.mock(WithDefinitions.class);
    float lineLeft = BORDER_LEFT + EYELET_MARGIN;
    float lineBottom = BORDER_BOTTOM + EYELET_MARGIN;

    withDefinitions.setEyeletDistMinH(20);
    withDefinitions.setEyeletDistMinV(20);
    withDefinitions.setMirror(false);

    withDefinitions.computeEyelets(pdfWriter);

    Mockito.verify(pdfContentByte).addTemplate(
        Mockito.any(PdfImportedPage.class),
        Mockito.eq(lineLeft),
        Mockito.eq(lineBottom)
    );

更新下面是异常消息:

Wanted but not invoked:
 pdfContentByte.addTemplate(
  <any>,
  62.36221,
  62.36221
);
-> at ...tools.pdf.superimpose.WithDefinitionsTest.computeEyeletsNoMirror(WithDefinitionsTest.java:336)
Actually, there were zero interactions with this mock.

更新2用真实实例替换mocked WithDefinitions对象后,我得到以下输出:

Argument(s) are different! Wanted:
pdfContentByte.addTemplate(
  <any>,
  62.36221,
  62.36221
);
-> at ...tools.pdf.superimpose.WithDefinitionsTest.computeEyeletsNoMirror(WithDefinitionsTest.java:336)
Actual invocation has different arguments:
pdfContentByte.addTemplate(
  null,
  48.18898,
  48.18898
);
-> at ...tools.pdf.superimpose.WithDefinitions.setEyelet(WithDefinitions.java:850)

共有1个答案

寇涵容
2023-03-14

你在嘲笑你正在测试的对象。那没道理。您应该创建一个真实的WithDefinitions对象,并调用它的真实方法来测试它。如果您模拟它,根据定义,它的所有方法都被不执行任何操作的模拟实现所替换。

替换

WithDefinitions withDefinitions = Mockito.mock(WithDefinitions.class);

通过类似的东西

WithDefinitions withDefinitions = new WithDefinitions();
 类似资料: