001 package org.junit.experimental.results; 002 003 import java.io.ByteArrayOutputStream; 004 import java.io.PrintStream; 005 import java.util.List; 006 007 import org.junit.internal.TextListener; 008 import org.junit.runner.JUnitCore; 009 import org.junit.runner.Request; 010 import org.junit.runner.Result; 011 import org.junit.runner.notification.Failure; 012 013 /** 014 * A test result that prints nicely in error messages. 015 * This is only intended to be used in JUnit self-tests. 016 * For example: 017 * 018 * <pre> 019 * assertThat(testResult(HasExpectedException.class), isSuccessful()); 020 * </pre> 021 */ 022 public class PrintableResult { 023 private Result result; 024 025 /** 026 * The result of running JUnit on {@code type} 027 */ 028 public static PrintableResult testResult(Class<?> type) { 029 return testResult(Request.aClass(type)); 030 } 031 032 /** 033 * The result of running JUnit on Request {@code request} 034 */ 035 public static PrintableResult testResult(Request request) { 036 return new PrintableResult(new JUnitCore().run(request)); 037 } 038 039 /** 040 * A result that includes the given {@code failures} 041 */ 042 public PrintableResult(List<Failure> failures) { 043 this(new FailureList(failures).result()); 044 } 045 046 private PrintableResult(Result result) { 047 this.result = result; 048 } 049 050 /** 051 * Returns the number of failures in this result. 052 */ 053 public int failureCount() { 054 return result.getFailures().size(); 055 } 056 057 @Override 058 public String toString() { 059 ByteArrayOutputStream stream = new ByteArrayOutputStream(); 060 new TextListener(new PrintStream(stream)).testRunFinished(result); 061 return stream.toString(); 062 } 063 }