diff --git a/Doc/Sd1/appendix.xml b/Doc/Sd1/appendix.xml index acf7e815e85d7f5ae717417f26d62328b07e35e2..0449252e91f8755cab74bbfec35a985621d12e3f 100644 --- a/Doc/Sd1/appendix.xml +++ b/Doc/Sd1/appendix.xml @@ -478,6 +478,71 @@ java -jar ~/.m2/repository/de/hdm-stuttgart/mi/sd1/grep/0.9/grep-0.9.jar $* <programlisting language="none">> cat Testdata/input.txt | ./bin/mygrep red The red cross acts worldwide</programlisting> </listitem> + + <listitem> + <para>Testing requires capturing of output being generated by e.g. + <methodname + xlink:href="https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#out">System.out</methodname><code>.</code><methodname + xlink:href="https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html#println-java.lang.String-">println(...)</methodname> + calls. Consider the following code writing the string <quote>Hello + World!</quote> to standard output:</para> + + <programlisting language="java">public class App { + /** + * @param args Unused + */ + public static void main( String[] args ) { + System.out.print( "Hello World!" ); + } +}</programlisting> + + <para>We want to set up a <productname>Junit</productname> test + which captures the output to compare it with the expected string + value <code>"Hello World!"</code>. Following <uri + xlink:href="http://stackoverflow.com/questions/1119385/junit-test-for-system-out-println">http://stackoverflow.com/questions/1119385/junit-test-for-system-out-println</uri> + we redefine the standard output stream by an private instance of + <classname + xlink:href="https://docs.oracle.com/javase/8/docs/api/java/io/ByteArrayOutputStream.html">java.io.ByteArrayOutputStream</classname>. + Due to <productname>Junit</productname>'s @Before and @After + annotations this instance replaces <classname + xlink:href="https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#out">System.out</classname> + during our tests:</para> + + <programlisting language="java">import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Unit test for simple App. + */ +public class AppTest { + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + + @Before + public void setUpStreams() { + System.setOut(new PrintStream(outContent)); + } + + @After + public void cleanUpStreams() { + System.setOut(null); + outContent.reset(); + } + + /** + * Test method accessing output generated by System.out.println(...) calls. + */ + @Test + public void testApp() { + App.main(new String[]{}); // Calling main() method printing "Hello World!" + Assert.assertEquals("Hello World!", outContent.toString()); + } +}</programlisting> + </listitem> </orderedlist> </tip> </section>