Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit test a static void method [duplicate]

So I created a log function so I can see the date of every action. I now want to unittest them. Because the function uses a void, I can't test the output.

I might change the void to a String, but then the point of using it as a void would be gone!

What are my options?

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);
}

Thanks :D

like image 612
bobbybouwmann Avatar asked May 24 '26 17:05

bobbybouwmann


2 Answers

You need to test the side effects of your method. In this case, the side effect you want to observe is something getting written to System.out. You can use System.setOut to install your own OutputStream. From there you can verify that something was written to it.

For instance:

String s = "your message";
ByteArrayOutputStream sink = new ByteArrayOutputStream();
System.setOut(new PrintStream(sink, true));
log(s);
assertThat(new String(sink.toByteArray()), containsString(s));
like image 194
Jeffrey Avatar answered May 26 '26 07:05

Jeffrey


You can use the library System Rules. It automatically sets the System.out back after the test.

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

  @Test
  public void testLoggerEmptyString() {
    log("hello world");
    assertEquals("hello world", log.getLog());
  }
}
like image 40
Stefan Birkner Avatar answered May 26 '26 06:05

Stefan Birkner