[英]Unable to write Mockito test case for my void method
I need to test this code with Mockito (JUnit): 我需要使用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);
}
}
}
I search so many examples google but still not getting any idea. 我在Google搜索了很多示例,但仍然没有任何想法。
You can configure System
with an instance of PrintStream
which you can then assert against after invoking Calculation.logTimeTaken
. 您可以使用PrintStream
实例配置System
,然后在调用Calculation.logTimeTaken
之后可以对其断言。
Here's an example: 这是一个例子:
@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());
}
Note: there is no need for Mockito here, this is just vanilla JUnit, no mocking. 注意:这里不需要Mockito,这只是原始的JUnit,没有模拟。
But , it might be a better design to refactor logTimeTaken
into two distinct aspects: 但是 ,将logTimeTaken
重构为两个不同的方面可能是一个更好的设计:
For example: 例如:
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);
}
Then testing createTimeTakenMessage
is trivial and you might even choose not to test logTimeTaken
at all since all it does is invoke a System method. 然后测试createTimeTakenMessage
是微不足道的,您甚至可以选择根本不测试logTimeTaken
,因为它所做的只是调用System方法。 Or, perhaps you would hide the 'log action' behind an interface with an implementation using System.out
now and perhaps, later, other implementations using a formal logging framework such as Logback. 或者,您可能会现在使用System.out
的实现将接口中的“日志操作”隐藏起来,而稍后可能会将使用正式日志记录框架(例如Logback)的其他实现隐藏起来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.