01: package org.junit.runner.notification;
02:
03: import java.io.PrintWriter;
04: import java.io.StringWriter;
05:
06: import org.junit.runner.Description;
07:
08: /**
09: * A <code>Failure</code> holds a description of the failed test and the
10: * exception that was thrown while running it. In most cases the {@link org.junit.runner.Description}
11: * will be of a single test. However, if problems are encountered while constructing the
12: * test (for example, if a {@link org.junit.BeforeClass} method is not static), it may describe
13: * something other than a single test.
14: */
15: public class Failure {
16: private final Description fDescription;
17: private Throwable fThrownException;
18:
19: /**
20: * Constructs a <code>Failure</code> with the given description and exception.
21: * @param description a {@link org.junit.runner.Description} of the test that failed
22: * @param thrownException the exception that was thrown while running the test
23: */
24: public Failure(Description description, Throwable thrownException) {
25: fThrownException = thrownException;
26: fDescription = description;
27: }
28:
29: /**
30: * @return a user-understandable label for the test
31: */
32: public String getTestHeader() {
33: return fDescription.getDisplayName();
34: }
35:
36: /**
37: * @return the raw description of the context of the failure.
38: */
39: public Description getDescription() {
40: return fDescription;
41: }
42:
43: /**
44: * @return the exception thrown
45: */
46:
47: public Throwable getException() {
48: return fThrownException;
49: }
50:
51: @Override
52: public String toString() {
53: StringBuffer buffer = new StringBuffer();
54: buffer.append(getTestHeader() + ": "
55: + fThrownException.getMessage());
56: return buffer.toString();
57: }
58:
59: /**
60: * Convenience method
61: * @return the printed form of the exception
62: */
63: public String getTrace() {
64: StringWriter stringWriter = new StringWriter();
65: PrintWriter writer = new PrintWriter(stringWriter);
66: getException().printStackTrace(writer);
67: StringBuffer buffer = stringWriter.getBuffer();
68: return buffer.toString();
69: }
70:
71: /**
72: * Convenience method
73: * @return the message of the thrown exception
74: */
75: public String getMessage() {
76: return getException().getMessage();
77: }
78: }
|