2013-12-17 3 views
2

그래서 모든 작업의 ​​날짜를 볼 수 있도록 로그 함수를 만들었습니다. 나는 이제 그들을 단위 테스트하고 싶다. 함수는 void를 사용하기 때문에 출력을 테스트 할 수 없습니다.JUnit static void 메서드

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 Rules을 사용할 수 있습니다

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

또는

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

하여 코드에서 사용할 수 있습니다. 테스트 후 자동으로 System.out을 다시 설정합니다.

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

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