1 package org.junit.experimental.results; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.PrintStream; 5 import java.util.List; 6 7 import org.junit.internal.TextListener; 8 import org.junit.runner.JUnitCore; 9 import org.junit.runner.Request; 10 import org.junit.runner.Result; 11 import org.junit.runner.notification.Failure; 12 13 /** 14 * A test result that prints nicely in error messages. 15 * This is only intended to be used in JUnit self-tests. 16 * For example: 17 * 18 * <pre> 19 * assertThat(testResult(HasExpectedException.class), isSuccessful()); 20 * </pre> 21 */ 22 public class PrintableResult { 23 private Result result; 24 25 /** 26 * The result of running JUnit on {@code type} 27 */ 28 public static PrintableResult testResult(Class<?> type) { 29 return testResult(Request.aClass(type)); 30 } 31 32 /** 33 * The result of running JUnit on Request {@code request} 34 */ 35 public static PrintableResult testResult(Request request) { 36 return new PrintableResult(new JUnitCore().run(request)); 37 } 38 39 /** 40 * A result that includes the given {@code failures} 41 */ 42 public PrintableResult(List<Failure> failures) { 43 this(new FailureList(failures).result()); 44 } 45 46 private PrintableResult(Result result) { 47 this.result = result; 48 } 49 50 /** 51 * Returns the number of failures in this result. 52 */ 53 public int failureCount() { 54 return result.getFailures().size(); 55 } 56 57 @Override 58 public String toString() { 59 ByteArrayOutputStream stream = new ByteArrayOutputStream(); 60 new TextListener(new PrintStream(stream)).testRunFinished(result); 61 return stream.toString(); 62 } 63 }