1// Copyright 2010 Google Inc. All Rights Reserved.
2
3package org.junit.runners.model;
4
5import java.util.ArrayList;
6import java.util.Collections;
7import java.util.List;
8
9/**
10 * Collects multiple {@code Throwable}s into one exception.
11 */
12public class MultipleFailureException extends Exception {
13	private static final long serialVersionUID= 1L;
14
15	private final List<Throwable> fErrors;
16
17	public MultipleFailureException(List<Throwable> errors) {
18		fErrors= new ArrayList<Throwable>(errors);
19	}
20
21	public List<Throwable> getFailures() {
22		return Collections.unmodifiableList(fErrors);
23	}
24
25	@Override
26	public String getMessage() {
27		StringBuilder sb = new StringBuilder(
28				String.format("There were %d errors:", fErrors.size()));
29		for (Throwable e : fErrors) {
30			sb.append(String.format("\n  %s(%s)", e.getClass().getName(), e.getMessage()));
31		}
32		return sb.toString();
33	}
34
35	/**
36	 * Asserts that a list of throwables is empty. If it isn't empty,
37	 * will throw {@link MultipleFailureException} (if there are
38	 * multiple throwables in the list) or the first element in the list
39	 * (if there is only one element).
40	 *
41	 * @param errors list to check
42	 * @throws Throwable if the list is not empty
43	 */
44	@SuppressWarnings("deprecation")
45	public static void assertEmpty(List<Throwable> errors) throws Throwable {
46		if (errors.isEmpty())
47			return;
48		if (errors.size() == 1)
49			throw errors.get(0);
50
51		/*
52		 * Many places in the code are documented to throw
53		 * org.junit.internal.runners.model.MultipleFailureException.
54		 * That class now extends this one, so we throw the internal
55		 * exception in case developers have tests that catch
56		 * MultipleFailureException.
57		 */
58		throw new org.junit.internal.runners.model.MultipleFailureException(errors);
59	}
60}
61