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 021 /* 022 * We have to use the f prefix until the next major release to ensure 023 * serialization compatibility. 024 * See https://github.com/junit-team/junit4/issues/976 025 */ 026 private final Description fDescription; 027 private final Throwable fThrownException; 028 029 /** 030 * Constructs a <code>Failure</code> with the given description and exception. 031 * 032 * @param description a {@link org.junit.runner.Description} of the test that failed 033 * @param thrownException the exception that was thrown while running the test 034 */ 035 public Failure(Description description, Throwable thrownException) { 036 this.fThrownException = thrownException; 037 this.fDescription = description; 038 } 039 040 /** 041 * @return a user-understandable label for the test 042 */ 043 public String getTestHeader() { 044 return fDescription.getDisplayName(); 045 } 046 047 /** 048 * @return the raw description of the context of the failure. 049 */ 050 public Description getDescription() { 051 return fDescription; 052 } 053 054 /** 055 * @return the exception thrown 056 */ 057 058 public Throwable getException() { 059 return fThrownException; 060 } 061 062 @Override 063 public String toString() { 064 return getTestHeader() + ": " + fThrownException.getMessage(); 065 } 066 067 /** 068 * Convenience method 069 * 070 * @return the printed form of the exception 071 */ 072 public String getTrace() { 073 StringWriter stringWriter = new StringWriter(); 074 PrintWriter writer = new PrintWriter(stringWriter); 075 getException().printStackTrace(writer); 076 return stringWriter.toString(); 077 } 078 079 /** 080 * Convenience method 081 * 082 * @return the message of the thrown exception 083 */ 084 public String getMessage() { 085 return getException().getMessage(); 086 } 087 }