1 package org.junit.tests.listening; 2 3 import static org.hamcrest.core.IsNot.not; 4 import static org.hamcrest.core.StringContains.containsString; 5 import static org.junit.Assert.assertThat; 6 7 import java.io.ByteArrayOutputStream; 8 import java.io.OutputStream; 9 import java.io.PrintStream; 10 11 import junit.framework.TestCase; 12 import org.junit.Test; 13 import org.junit.internal.TextListener; 14 import org.junit.runner.JUnitCore; 15 import org.junit.tests.TestSystem; 16 17 public class TextListenerTest extends TestCase { 18 19 private JUnitCore runner; 20 private OutputStream results; 21 22 @Override 23 public void setUp() { 24 runner = new JUnitCore(); 25 TestSystem system = new TestSystem(); 26 results = system.outContents(); 27 runner.addListener(new TextListener(system)); 28 } 29 30 public static class OneTest { 31 @Test 32 public void one() { 33 } 34 } 35 36 public void testSuccess() throws Exception { 37 runner.run(OneTest.class); 38 assertTrue(results.toString().startsWith(convert(".\nTime: "))); 39 assertTrue(results.toString().endsWith(convert("\n\nOK (1 test)\n\n"))); 40 } 41 42 public static class ErrorTest { 43 @Test 44 public void error() throws Exception { 45 throw new Exception(); 46 } 47 } 48 49 public void testError() throws Exception { 50 runner.run(ErrorTest.class); 51 assertTrue(results.toString().startsWith(convert(".E\nTime: "))); 52 assertTrue(results.toString().indexOf(convert("\nThere was 1 failure:\n1) error(org.junit.tests.listening.TextListenerTest$ErrorTest)\njava.lang.Exception")) != -1); 53 } 54 55 public static class Time { 56 @Test 57 public void time() { 58 } 59 } 60 61 public void testTime() { 62 runner.run(Time.class); 63 assertThat(results.toString(), containsString("Time: ")); 64 assertThat(results.toString(), not(containsString(convert("Time: \n")))); 65 } 66 67 private String convert(String string) { 68 OutputStream resultsStream = new ByteArrayOutputStream(); 69 PrintStream writer = new PrintStream(resultsStream); 70 writer.println(); 71 return string.replace("\n", resultsStream.toString()); 72 } 73 }