001 package org.junit.runner.notification;
002
003 import java.io.Serializable;
004
005 import org.junit.internal.Throwables;
006 import org.junit.runner.Description;
007
008 /**
009 * A <code>Failure</code> holds a description of the failed test and the
010 * exception that was thrown while running it. In most cases the {@link org.junit.runner.Description}
011 * will be of a single test. However, if problems are encountered while constructing the
012 * test (for example, if a {@link org.junit.BeforeClass} method is not static), it may describe
013 * something other than a single test.
014 *
015 * @since 4.0
016 */
017 public class Failure implements Serializable {
018 private static final long serialVersionUID = 1L;
019
020 /*
021 * We have to use the f prefix until the next major release to ensure
022 * serialization compatibility.
023 * See https://github.com/junit-team/junit4/issues/976
024 */
025 private final Description fDescription;
026 private final Throwable fThrownException;
027
028 /**
029 * Constructs a <code>Failure</code> with the given description and exception.
030 *
031 * @param description a {@link org.junit.runner.Description} of the test that failed
032 * @param thrownException the exception that was thrown while running the test
033 */
034 public Failure(Description description, Throwable thrownException) {
035 this.fThrownException = thrownException;
036 this.fDescription = description;
037 }
038
039 /**
040 * @return a user-understandable label for the test
041 */
042 public String getTestHeader() {
043 return fDescription.getDisplayName();
044 }
045
046 /**
047 * @return the raw description of the context of the failure.
048 */
049 public Description getDescription() {
050 return fDescription;
051 }
052
053 /**
054 * @return the exception thrown
055 */
056
057 public Throwable getException() {
058 return fThrownException;
059 }
060
061 @Override
062 public String toString() {
063 return getTestHeader() + ": " + fThrownException.getMessage();
064 }
065
066 /**
067 * Gets the printed form of the exception and its stack trace.
068 */
069 public String getTrace() {
070 return Throwables.getStacktrace(getException());
071 }
072
073 /**
074 * Gets a the printed form of the exception, with a trimmed version of the stack trace.
075 * This method will attempt to filter out frames of the stack trace that are below
076 * the test method call.
077 */
078 public String getTrimmedTrace() {
079 return Throwables.getTrimmedStackTrace(getException());
080 }
081
082 /**
083 * Convenience method
084 *
085 * @return the message of the thrown exception
086 */
087 public String getMessage() {
088 return getException().getMessage();
089 }
090 }