Its very rare the case when you will have to test things such as an String being printed in the console or a System property being set from the program... But in occasions it happens that.
Last week I discovered a library called system-rules, from Stefan Birkner. http://stefanbirkner.github.io/system-rules/
It is really interesting and easy to use, it can help you easily do tests that involve java.lang.System
Lets just quickly saw an example.
Imagine that for some reason you want to test that the console prints some message... I don't know you, but the only way I know to do that, is to redirect the stream that goes to the console, to something that you can control and read from(e.g a file, a log...). This kind of test would have lots of boiler plate. It would look somehow like this:
@Test
public void consoleOutputOldSchoolTest() throws FileNotFoundException {
//Create some text file where the output will be redirected, so you can make an assertion later.
File testingFile = new File("testingFile.txt");
//Create a testing stream and give the file to it
PrintStream testingStream = new PrintStream(testingFile);
//Keep a copy of the old console output stream
PrintStream consoleStream = new PrintStream(System.out);
//Reset the object out to the new stream
System.setOut(testingStream);
//Write something to the "console"
System.out.print("test");
//Rewire back to the original console output
System.setOut(consoleStream);
//Just an informative message
System.out.println("all back to normal");
//Read the output that we are testing
String output = new Scanner(testingFile).nextLine();
//Do your assertion
assertThat(output, is("test"));
//Delete the test file
testingFile.delete();
}
With Stefan's library you can test the messages that go the terminal in the blink of an eye:
@Rule
public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();
@Test
public void systemRulesLibraryConsoleOutputTest() {
System.out.print("test");
assertThat(systemOutRule.getLog(), is("test"));
}
Ok, now back to work now ;)