001package org.junit.experimental.results;
002
003import java.io.ByteArrayOutputStream;
004import java.io.PrintStream;
005import java.util.List;
006
007import org.junit.internal.TextListener;
008import org.junit.runner.JUnitCore;
009import org.junit.runner.Request;
010import org.junit.runner.Result;
011import 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 */
022public 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    /**
058     * Returns the failures in this result.
059     *
060     * @since 4.13
061     */
062    public List<Failure> failures() {
063        return result.getFailures();
064    }
065
066    @Override
067    public String toString() {
068        ByteArrayOutputStream stream = new ByteArrayOutputStream();
069        new TextListener(new PrintStream(stream)).testRunFinished(result);
070        return stream.toString();
071    }
072}