001 package org.junit.runners.model; 002 003 import java.util.ArrayList; 004 import java.util.Collections; 005 import java.util.List; 006 007 import org.junit.internal.Throwables; 008 009 /** 010 * Collects multiple {@code Throwable}s into one exception. 011 * 012 * @since 4.9 013 */ 014 public class MultipleFailureException extends Exception { 015 private static final long serialVersionUID = 1L; 016 017 private final List<Throwable> errors; 018 019 public MultipleFailureException(List<Throwable> errors) { 020 this.errors = new ArrayList<Throwable>(errors); 021 } 022 023 public List<Throwable> getFailures() { 024 return Collections.unmodifiableList(errors); 025 } 026 027 @Override 028 public String getMessage() { 029 StringBuilder sb = new StringBuilder( 030 String.format("There were %d errors:", errors.size())); 031 for (Throwable e : errors) { 032 sb.append(String.format("\n %s(%s)", e.getClass().getName(), e.getMessage())); 033 } 034 return sb.toString(); 035 } 036 037 /** 038 * Asserts that a list of throwables is empty. If it isn't empty, 039 * will throw {@link MultipleFailureException} (if there are 040 * multiple throwables in the list) or the first element in the list 041 * (if there is only one element). 042 * 043 * @param errors list to check 044 * @throws Exception or Error if the list is not empty 045 */ 046 @SuppressWarnings("deprecation") 047 public static void assertEmpty(List<Throwable> errors) throws Exception { 048 if (errors.isEmpty()) { 049 return; 050 } 051 if (errors.size() == 1) { 052 throw Throwables.rethrowAsException(errors.get(0)); 053 } 054 055 /* 056 * Many places in the code are documented to throw 057 * org.junit.internal.runners.model.MultipleFailureException. 058 * That class now extends this one, so we throw the internal 059 * exception in case developers have tests that catch 060 * MultipleFailureException. 061 */ 062 throw new org.junit.internal.runners.model.MultipleFailureException(errors); 063 } 064 }