2013-12-17 96 views
2

所以我创建了一个日志函数,以便我可以看到每个动作的日期。我现在想单元测试他们。因为该函数使用void,所以我无法测试输出。JUnit测试静态无效方法

我可能会将void更改为一个String,但随后将它作为void使用的点将消失!

我有什么选择?

public class Logger { 

    public static void log(String s) { 
     Date d = new Date(); 
     SimpleDateFormat ft = 
       new SimpleDateFormat ("yyyy.MM.dd '-' hh:mm:ss"); 
     System.out.println("[" + ft.format(d) + "]: " + s); 
    } 

} 

的JUnit

@Test 
public void testLoggerEmptyString() { 
    String s = ""; 
    log(s); 
} 

感谢:d

回答

5

你需要测试你的方法的副作用。在这种情况下,您想观察的副作用是写入System.out的内容。您可以使用System.setOut安装您自己的OutputStream。从那里你可以验证写了什么。

例如:

String s = "your message"; 
ByteArrayOutputStream sink = new ByteArrayOutputStream(); 
System.setOut(new PrintStream(sink, true)); 
log(s); 
assertThat(new String(sink.toByteArray()), containsString(s)); 
+0

+1这个想法! –

+0

只需记住在完成后设置System.out! – dkatzel

0

我可能会改变无效的字符串,但是如果使用它作为一个空白点就会消失!

我不这么认为。如果你的方法是这样的:

public static String getLogMessage(String s) { 
    Date d = new Date(); 
    SimpleDateFormat ft = new SimpleDateFormat ("yyyy.MM.dd '-' hh:mm:ss"); 
    return String.format("[%s] %s", ft.format(d), s); 
} 

您可以测试输出,并在代码中使用它

System.out.println(Whatever.getLogMessage("Foo for the world")); 

甚至

System.err.println(Whatever.getLogMessage("Holy shit!")); 
1

您可以使用该库System Rules。在测试之后它会自动设置System.out

public void MyTest { 
    @Rule 
    public final StandardOutputStreamLog log = new StandardOutputStreamLog(); 

    @Test 
    public void testLoggerEmptyString() { 
    log("hello world"); 
    assertEquals("hello world", log.getLog()); 
    } 
}