001// Copyright 2010 Google Inc. All Rights Reserved. 002 003package org.junit.runners.model; 004 005import java.util.ArrayList; 006import java.util.Collections; 007import java.util.List; 008 009/** 010 * Collects multiple {@code Throwable}s into one exception. 011 * 012 * @since 4.9 013 */ 014public class MultipleFailureException extends Exception { 015 private static final long serialVersionUID = 1L; 016 017 private final List<Throwable> fErrors; 018 019 public MultipleFailureException(List<Throwable> errors) { 020 fErrors = new ArrayList<Throwable>(errors); 021 } 022 023 public List<Throwable> getFailures() { 024 return Collections.unmodifiableList(fErrors); 025 } 026 027 @Override 028 public String getMessage() { 029 StringBuilder sb = new StringBuilder( 030 String.format("There were %d errors:", fErrors.size())); 031 for (Throwable e : fErrors) { 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 Throwable if the list is not empty 045 */ 046 @SuppressWarnings("deprecation") 047 public static void assertEmpty(List<Throwable> errors) throws Throwable { 048 if (errors.isEmpty()) { 049 return; 050 } 051 if (errors.size() == 1) { 052 throw 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}