001    package org.junit.runner.notification;
002    
003    import java.io.PrintWriter;
004    import java.io.Serializable;
005    import java.io.StringWriter;
006    
007    import 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     */
018    public class Failure implements Serializable {
019        private static final long serialVersionUID = 1L;
020        private final Description description;
021        private final Throwable thrownException;
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            this.thrownException = thrownException;
031            this.description = description;
032        }
033    
034        /**
035         * @return a user-understandable label for the test
036         */
037        public String getTestHeader() {
038            return description.getDisplayName();
039        }
040    
041        /**
042         * @return the raw description of the context of the failure.
043         */
044        public Description getDescription() {
045            return description;
046        }
047    
048        /**
049         * @return the exception thrown
050         */
051    
052        public Throwable getException() {
053            return thrownException;
054        }
055    
056        @Override
057        public String toString() {
058            return getTestHeader() + ": " + thrownException.getMessage();
059        }
060    
061        /**
062         * Convenience method
063         *
064         * @return the printed form of the exception
065         */
066        public String getTrace() {
067            StringWriter stringWriter = new StringWriter();
068            PrintWriter writer = new PrintWriter(stringWriter);
069            getException().printStackTrace(writer);
070            return stringWriter.toString();
071        }
072    
073        /**
074         * Convenience method
075         *
076         * @return the message of the thrown exception
077         */
078        public String getMessage() {
079            return getException().getMessage();
080        }
081    }