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 /*
018 * We have to use the f prefix until the next major release to ensure
019 * serialization compatibility.
020 * See https://github.com/junit-team/junit/issues/976
021 */
022 private final List<Throwable> fErrors;
023
024 public MultipleFailureException(List<Throwable> errors) {
025 this.fErrors = new ArrayList<Throwable>(errors);
026 }
027
028 public List<Throwable> getFailures() {
029 return Collections.unmodifiableList(fErrors);
030 }
031
032 @Override
033 public String getMessage() {
034 StringBuilder sb = new StringBuilder(
035 String.format("There were %d errors:", fErrors.size()));
036 for (Throwable e : fErrors) {
037 sb.append(String.format("\n %s(%s)", e.getClass().getName(), e.getMessage()));
038 }
039 return sb.toString();
040 }
041
042 /**
043 * Asserts that a list of throwables is empty. If it isn't empty,
044 * will throw {@link MultipleFailureException} (if there are
045 * multiple throwables in the list) or the first element in the list
046 * (if there is only one element).
047 *
048 * @param errors list to check
049 * @throws Exception or Error if the list is not empty
050 */
051 @SuppressWarnings("deprecation")
052 public static void assertEmpty(List<Throwable> errors) throws Exception {
053 if (errors.isEmpty()) {
054 return;
055 }
056 if (errors.size() == 1) {
057 throw Throwables.rethrowAsException(errors.get(0));
058 }
059
060 /*
061 * Many places in the code are documented to throw
062 * org.junit.internal.runners.model.MultipleFailureException.
063 * That class now extends this one, so we throw the internal
064 * exception in case developers have tests that catch
065 * MultipleFailureException.
066 */
067 throw new org.junit.internal.runners.model.MultipleFailureException(errors);
068 }
069 }