Home | History | Annotate | Download | only in notification
      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 public class Failure implements Serializable {
     17 	private static final long serialVersionUID = 1L;
     18 	private final Description fDescription;
     19 	private final Throwable fThrownException;
     20 
     21 	/**
     22 	 * Constructs a <code>Failure</code> with the given description and exception.
     23 	 * @param description a {@link org.junit.runner.Description} of the test that failed
     24 	 * @param thrownException the exception that was thrown while running the test
     25 	 */
     26 	public Failure(Description description, Throwable thrownException) {
     27 		fThrownException = thrownException;
     28 		fDescription= description;
     29 	}
     30 
     31 	/**
     32 	 * @return a user-understandable label for the test
     33 	 */
     34 	public String getTestHeader() {
     35 		return fDescription.getDisplayName();
     36 	}
     37 
     38 	/**
     39 	 * @return the raw description of the context of the failure.
     40 	 */
     41 	public Description getDescription() {
     42 		return fDescription;
     43 	}
     44 
     45 	/**
     46 	 * @return the exception thrown
     47 	 */
     48 
     49 	public Throwable getException() {
     50 	    return fThrownException;
     51 	}
     52 
     53 	@Override
     54 	public String toString() {
     55 	    StringBuffer buffer= new StringBuffer();
     56 	    buffer.append(getTestHeader() + ": "+fThrownException.getMessage());
     57 	    return buffer.toString();
     58 	}
     59 
     60 	/**
     61 	 * Convenience method
     62 	 * @return the printed form of the exception
     63 	 */
     64 	public String getTrace() {
     65 		StringWriter stringWriter= new StringWriter();
     66 		PrintWriter writer= new PrintWriter(stringWriter);
     67 		getException().printStackTrace(writer);
     68 		StringBuffer buffer= stringWriter.getBuffer();
     69 		return buffer.toString();
     70 	}
     71 
     72 	/**
     73 	 * Convenience method
     74 	 * @return the message of the thrown exception
     75 	 */
     76 	public String getMessage() {
     77 		return getException().getMessage();
     78 	}
     79 }
     80