View Javadoc
1   package org.junit.rules;
2   
3   import static org.hamcrest.CoreMatchers.allOf;
4   import static org.junit.matchers.JUnitMatchers.isThrowable;
5   
6   import java.util.ArrayList;
7   import java.util.List;
8   
9   import org.hamcrest.Matcher;
10  
11  /**
12   * Builds special matcher used by {@link ExpectedException}.
13   */
14  class ExpectedExceptionMatcherBuilder {
15  
16      private final List<Matcher<?>> matchers = new ArrayList<Matcher<?>>();
17  
18      void add(Matcher<?> matcher) {
19          matchers.add(matcher);
20      }
21  
22      boolean expectsThrowable() {
23          return !matchers.isEmpty();
24      }
25  
26      Matcher<Throwable> build() {
27          return isThrowable(allOfTheMatchers());
28      }
29  
30      private Matcher<Throwable> allOfTheMatchers() {
31          if (matchers.size() == 1) {
32              return cast(matchers.get(0));
33          }
34          return allOf(castedMatchers());
35      }
36  
37      @SuppressWarnings({"unchecked", "rawtypes"})
38      private List<Matcher<? super Throwable>> castedMatchers() {
39          return new ArrayList<Matcher<? super Throwable>>((List) matchers);
40      }
41  
42      @SuppressWarnings("unchecked")
43      private Matcher<Throwable> cast(Matcher<?> singleMatcher) {
44          return (Matcher<Throwable>) singleMatcher;
45      }
46  }