1package org.junit.experimental.results;
2
3import java.io.ByteArrayOutputStream;
4import java.io.PrintStream;
5import java.util.List;
6
7import org.junit.internal.TextListener;
8import org.junit.runner.JUnitCore;
9import org.junit.runner.Request;
10import org.junit.runner.Result;
11import 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 */
22public class PrintableResult {
23	/**
24	 * The result of running JUnit on {@code type}
25	 */
26	public static PrintableResult testResult(Class<?> type) {
27		return testResult(Request.aClass(type));
28	}
29
30	/**
31	 * The result of running JUnit on Request {@code request}
32	 */
33	public static PrintableResult testResult(Request request) {
34		return new PrintableResult(new JUnitCore().run(request));
35	}
36
37	private Result result;
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	@Override
51	public String toString() {
52		ByteArrayOutputStream stream = new ByteArrayOutputStream();
53		new TextListener(new PrintStream(stream)).testRunFinished(result);
54		return stream.toString();
55	}
56
57	/**
58	 * Returns the number of failures in this result.
59	 */
60	public int failureCount() {
61		return result.getFailures().size();
62	}
63}