001package org.junit.runner.notification;
002
003import java.io.PrintWriter;
004import java.io.Serializable;
005import java.io.StringWriter;
006
007import org.junit.runner.Description;
008
009/**
010 * A <code>Failure</code> holds a description of the failed test and the
011 * exception that was thrown while running it. In most cases the {@link org.junit.runner.Description}
012 * will be of a single test. However, if problems are encountered while constructing the
013 * test (for example, if a {@link org.junit.BeforeClass} method is not static), it may describe
014 * something other than a single test.
015 *
016 * @since 4.0
017 */
018public class Failure implements Serializable {
019    private static final long serialVersionUID = 1L;
020    private final Description fDescription;
021    private final Throwable fThrownException;
022
023    /**
024     * Constructs a <code>Failure</code> with the given description and exception.
025     *
026     * @param description a {@link org.junit.runner.Description} of the test that failed
027     * @param thrownException the exception that was thrown while running the test
028     */
029    public Failure(Description description, Throwable thrownException) {
030        fThrownException = thrownException;
031        fDescription = description;
032    }
033
034    /**
035     * @return a user-understandable label for the test
036     */
037    public String getTestHeader() {
038        return fDescription.getDisplayName();
039    }
040
041    /**
042     * @return the raw description of the context of the failure.
043     */
044    public Description getDescription() {
045        return fDescription;
046    }
047
048    /**
049     * @return the exception thrown
050     */
051
052    public Throwable getException() {
053        return fThrownException;
054    }
055
056    @Override
057    public String toString() {
058        StringBuffer buffer = new StringBuffer();
059        buffer.append(getTestHeader() + ": " + fThrownException.getMessage());
060        return buffer.toString();
061    }
062
063    /**
064     * Convenience method
065     *
066     * @return the printed form of the exception
067     */
068    public String getTrace() {
069        StringWriter stringWriter = new StringWriter();
070        PrintWriter writer = new PrintWriter(stringWriter);
071        getException().printStackTrace(writer);
072        StringBuffer buffer = stringWriter.getBuffer();
073        return buffer.toString();
074    }
075
076    /**
077     * Convenience method
078     *
079     * @return the message of the thrown exception
080     */
081    public String getMessage() {
082        return getException().getMessage();
083    }
084}