You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mockito doNothing失效:Mock已创建注入但仍生成文件未跳过方法

使用Spire库实现Docx转PDF的测试问题

我用com.spire库开发Docx转PDF功能,当前要测试convertWordToPDF()方法的catch代码分支。转换功能本身正常,但测试时尝试用Mockito的doNothing()让Document的saveToFile()方法不执行任何操作,以此触发catch块,结果发现目标PDF文件仍然被创建,导致断言失败(预期返回false,实际返回true)。已通过调试确认Mock对象已创建且被正确交互,但问题依旧存在。

测试类代码

public class PDFConverterTest {
    PDFConverter converter;
    String outPdf = "src/test/resources/outputTest.pdf";
    String inDoc = "src/test/resources/inputTest.docx";
    
    @Test
    void testPDFNotCreated() {
        Document doc = mock(Document.class);
        converter = new PDFConverter(inDoc, outPdf, doc);
        doNothing().when(doc).saveToFile(anyString());

        assertFalse(converter.convertWordToPDF());

        verify(doc).saveToFile(outPdf);
    }
}

被测类代码

public class PDFConverter {
    private final Logger LOGGER = LogManager.getLogger();
    private final Path DOC_IN;
    private final Path PDF_OUT;
    private final Document DOC;

    public PDFConverter() throws IOException {
        super();
        DOC_IN = Paths.get("output.docx");
        PDF_OUT = Paths.get("output.pdf");
        DOC = new Document(Files.newInputStream(DOC_IN));
    }

    public PDFConverter(String inDoc, String outPDF, Document doc) {
        super();
        DOC_IN = Paths.get(inDoc);
        PDF_OUT = Paths.get(outPDF);
        DOC = doc;
    }

    public PDFConverter(String inDoc, String outPdf) {
        super();
        DOC_IN = Paths.get(inDoc);
        PDF_OUT = Paths.get(outPdf);
        DOC = new Document();
    }

    public boolean convertWordToPDF() {
        try {
            LOGGER.info("Converting to PDF...");
            DOC.saveToFile(Files.newOutputStream(PDF_OUT), FileFormat.PDF);
            LOGGER.info("Conversion complete.");
            if (Files.isRegularFile(PDF_OUT)) return true;
            else throw new IOException();
        } catch (IOException e) {
            LOGGER.error(e);
            LOGGER.error("Conversion failed. Please check file paths are correct and not empty and input is .docx and output is .pdf format.");
            return false;
        }
    }
}

抛出的错误信息

org.opentest4j.AssertionFailedError: 
Expected :false
Actual   :true

内容的提问来源于stack exchange,提问作者AceKokuren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 21:20:28