• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package org.junit.runner.notification;
2 
3 import java.io.PrintWriter;
4 import java.io.Serializable;
5 import java.io.StringWriter;
6 
7 import org.junit.runner.Description;
8 
9 /**
10  * A <code>Failure</code> holds a description of the failed test and the
11  * exception that was thrown while running it. In most cases the {@link org.junit.runner.Description}
12  * will be of a single test. However, if problems are encountered while constructing the
13  * test (for example, if a {@link org.junit.BeforeClass} method is not static), it may describe
14  * something other than a single test.
15  *
16  * @since 4.0
17  */
18 public class Failure implements Serializable {
19     private static final long serialVersionUID = 1L;
20 
21     /*
22      * We have to use the f prefix until the next major release to ensure
23      * serialization compatibility.
24      * See https://github.com/junit-team/junit/issues/976
25      */
26     private final Description fDescription;
27     private final Throwable fThrownException;
28 
29     /**
30      * Constructs a <code>Failure</code> with the given description and exception.
31      *
32      * @param description a {@link org.junit.runner.Description} of the test that failed
33      * @param thrownException the exception that was thrown while running the test
34      */
Failure(Description description, Throwable thrownException)35     public Failure(Description description, Throwable thrownException) {
36         this.fThrownException = thrownException;
37         this.fDescription = description;
38     }
39 
40     /**
41      * @return a user-understandable label for the test
42      */
getTestHeader()43     public String getTestHeader() {
44         return fDescription.getDisplayName();
45     }
46 
47     /**
48      * @return the raw description of the context of the failure.
49      */
getDescription()50     public Description getDescription() {
51         return fDescription;
52     }
53 
54     /**
55      * @return the exception thrown
56      */
57 
getException()58     public Throwable getException() {
59         return fThrownException;
60     }
61 
62     @Override
toString()63     public String toString() {
64         return getTestHeader() + ": " + fThrownException.getMessage();
65     }
66 
67     /**
68      * Convenience method
69      *
70      * @return the printed form of the exception
71      */
getTrace()72     public String getTrace() {
73         StringWriter stringWriter = new StringWriter();
74         PrintWriter writer = new PrintWriter(stringWriter);
75         getException().printStackTrace(writer);
76         return stringWriter.toString();
77     }
78 
79     /**
80      * Convenience method
81      *
82      * @return the message of the thrown exception
83      */
getMessage()84     public String getMessage() {
85         return getException().getMessage();
86     }
87 }
88