Test that method was called

java, junit, unit-testing

Solution

As for whether it is worth testing, it depends on why your are outputting. I usually do test System.out calls when writing command line utilities because that is the user interface and the text output matters. It's not even hard to do - just regular Java code.

The below technique shows how you can capture the values of System.out. You don't even need a mock framework. Note that it stores the "real" System.out so it can put it back at the end. If you don't do this, your other tests/code can quickly become confusing.

import static org.junit.Assert.*;

import java.io.*;

import org.junit.*;

public class ConsoleHandlerTest {

    private PrintStream originalSysOut;
    private ByteArrayOutputStream mockOut;

    @Before
    public void setSysOut() {
        originalSysOut = System.out;
        mockOut = new ByteArrayOutputStream();
        System.setOut(new PrintStream(mockOut));
    }

    @After
    public void restoreSysOut() {
        System.setOut(originalSysOut);
    }

    @Test
    public void outputIsCorrect() {
        new ConsoleHandler().write("hello");
            assertEquals("message output", "hello".trim(), mockOut.toString().trim());
    }

}

Problem

Very very simple class: ``` public class ConsoleHandler { public void write(String message) { System.out.println(message); } } ``` How do I test that when I call `write("hello")`, `System.out.println("hello")` is called? And also, is this unit test even worth it?

Original source

Related problems