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