有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法为我的void方法编写Mockito测试用例

我需要用Mockito(JUnit)测试这段代码:

public class Calculation {

    public void logTimeTaken(String label, long estimatedTime, int size, boolean isDebug) {
       String out = label + " took " + TimeUnit.MILLISECONDS.convert(estimatedTime, TimeUnit.NANOSECONDS) + " milliseconds for " + size + " events!";
        if (isDebug) {
            System.out.println(out);
        } else {
            System.out.println(out);
        }
    }
}

我在谷歌上搜索了这么多的例子,但仍然没有得到任何想法


共 (1) 个答案

  1. # 1 楼答案

    您可以使用PrintStream的实例配置System,然后在调用Calculation.logTimeTaken后对其进行断言

    下面是一个例子:

    @Test
    public void canLogTimeTaken() {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        PrintStream out = new PrintStream(bout);
        System.setOut(out);
    
        Calculation sut = new Calculation();
        sut.logTimeTaken("label", 20 , 2, false);
        assertEquals("if isDebug is false label took 0 milliseconds for 2 events!\n", bout.toString());
    }
    

    注意:这里不需要Mockito,这只是香草JUnit,没有Mockito

    但是,将logTimeTaken重构为两个不同的方面可能是更好的设计:

    • 导出日志消息
    • 记录那条信息

    例如:

    public String createTimeTakenMessage(String label, long estimatedTime, int size, boolean isDebug) {
        return label + " took " + TimeUnit.MILLISECONDS.convert(estimatedTime, TimeUnit.NANOSECONDS) + " milliseconds for " + size + " events!";
    }
    
    public void logTimeTaken(String message) {
        System.out.println(message);
    }
    

    那么测试createTimeTakenMessage就很简单了,你甚至可以选择根本不测试logTimeTaken,因为它所做的只是调用一个系统方法。或者,您可能会将“日志操作”隐藏在一个接口后面,该接口现在使用System.out实现,以后可能使用正式的日志框架(如Logback)实现其他实现