1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
|
12 | |
|
13 | |
|
14 | |
|
15 | |
|
16 | |
|
17 | |
package org.truth0; |
18 | |
|
19 | |
import java.util.ArrayList; |
20 | |
import java.util.List; |
21 | |
|
22 | |
import org.junit.rules.MethodRule; |
23 | |
import org.junit.runners.model.FrameworkMethod; |
24 | |
import org.junit.runners.model.Statement; |
25 | |
|
26 | |
import com.google.common.annotations.GwtIncompatible; |
27 | |
|
28 | |
@GwtIncompatible("JUnit4") |
29 | |
@SuppressWarnings("deprecation") |
30 | 0 | public class Expect extends TestVerb implements MethodRule { |
31 | 0 | protected static class ExpectationGatherer implements FailureStrategy { |
32 | 0 | List<String> messages = new ArrayList<String>(); |
33 | |
|
34 | |
@Override public void fail(String message) { |
35 | 0 | messages.add(message); |
36 | 0 | } |
37 | |
} |
38 | |
|
39 | |
private final ExpectationGatherer gatherer; |
40 | 0 | private boolean inRuleContext = false; |
41 | |
|
42 | |
public static Expect create() { |
43 | 0 | return new Expect(new ExpectationGatherer()); |
44 | |
} |
45 | |
|
46 | |
Expect(ExpectationGatherer gatherer) { |
47 | 0 | super(gatherer); |
48 | 0 | this.gatherer = gatherer; |
49 | 0 | } |
50 | |
|
51 | |
@Override |
52 | |
protected FailureStrategy getFailureStrategy() { |
53 | 0 | if (!inRuleContext) { |
54 | 0 | String message = "assertion made on Expect instance, but it's not enabled as a @Rule."; |
55 | 0 | throw new IllegalStateException(message); |
56 | |
} |
57 | 0 | return super.getFailureStrategy(); |
58 | |
} |
59 | |
|
60 | |
|
61 | |
@Override public Statement apply(final Statement base, |
62 | |
FrameworkMethod method, Object target) { |
63 | 0 | return new Statement() { |
64 | |
@Override public void evaluate() throws Throwable { |
65 | 0 | inRuleContext = true; |
66 | 0 | base.evaluate(); |
67 | 0 | inRuleContext = false; |
68 | 0 | if (!gatherer.messages.isEmpty()) { |
69 | 0 | StringBuilder message = new StringBuilder("All failed expectations:\n"); |
70 | 0 | for (int i = 0; i < gatherer.messages.size(); i++) { |
71 | 0 | message.append(" ").append(i + 1).append(". ") |
72 | |
.append(gatherer.messages.get(i)).append("\n"); |
73 | |
} |
74 | 0 | throw new AssertionError(message.toString()); |
75 | |
} |
76 | 0 | } |
77 | |
}; |
78 | |
} |
79 | |
} |