3

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

bobbybouwmann
  • 983
  • 3
  • 12
  • 24

3 Answers3

6

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));
Jeffrey
  • 44,417
  • 8
  • 90
  • 141
1

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());
  }
}
Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72
0

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

I don't think so. If your method would look like this:

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

You could test the output and use it in your code with

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

or even

System.err.println(Whatever.getLogMessage("Holy shit!"));
Martin Seeler
  • 6,874
  • 3
  • 33
  • 45