• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
add(Matcher<?> matcher)18     void add(Matcher<?> matcher) {
19         matchers.add(matcher);
20     }
21 
expectsThrowable()22     boolean expectsThrowable() {
23         return !matchers.isEmpty();
24     }
25 
build()26     Matcher<Throwable> build() {
27         return isThrowable(allOfTheMatchers());
28     }
29 
allOfTheMatchers()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"})
castedMatchers()38     private List<Matcher<? super Throwable>> castedMatchers() {
39         return new ArrayList<Matcher<? super Throwable>>((List) matchers);
40     }
41 
42     @SuppressWarnings("unchecked")
cast(Matcher<?> singleMatcher)43     private Matcher<Throwable> cast(Matcher<?> singleMatcher) {
44         return (Matcher<Throwable>) singleMatcher;
45     }
46 }
47