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 楼答案
您可以使用
PrintStream
的实例配置System
,然后在调用Calculation.logTimeTaken
后对其进行断言下面是一个例子:
注意:这里不需要Mockito,这只是香草JUnit,没有Mockito
但是,将
logTimeTaken
重构为两个不同的方面可能是更好的设计:例如:
那么测试
createTimeTakenMessage
就很简单了,你甚至可以选择根本不测试logTimeTaken
,因为它所做的只是调用一个系统方法。或者,您可能会将“日志操作”隐藏在一个接口后面,该接口现在使用System.out
实现,以后可能使用正式的日志框架(如Logback)实现其他实现