| 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 | 111 | public class Expect extends TestVerb implements MethodRule { |
| 31 | 35 | protected static class ExpectationGatherer implements FailureStrategy { |
| 32 | 35 | List<String> messages = new ArrayList<String>(); |
| 33 | |
|
| 34 | |
@Override public void fail(String message) { |
| 35 | 7 | messages.add(message); |
| 36 | 7 | } |
| 37 | |
} |
| 38 | |
|
| 39 | |
private final ExpectationGatherer gatherer; |
| 40 | 35 | private boolean inRuleContext = false; |
| 41 | |
|
| 42 | |
public static Expect create() { |
| 43 | 31 | return new Expect(new ExpectationGatherer()); |
| 44 | |
} |
| 45 | |
|
| 46 | |
Expect(ExpectationGatherer gatherer) { |
| 47 | 35 | super(gatherer); |
| 48 | 35 | this.gatherer = gatherer; |
| 49 | 35 | } |
| 50 | |
|
| 51 | |
@Override |
| 52 | |
protected FailureStrategy getFailureStrategy() { |
| 53 | 17 | if (!inRuleContext) { |
| 54 | 1 | String message = "assertion made on Expect instance, but it's not enabled as a @Rule."; |
| 55 | 1 | throw new IllegalStateException(message); |
| 56 | |
} |
| 57 | 16 | return super.getFailureStrategy(); |
| 58 | |
} |
| 59 | |
|
| 60 | |
|
| 61 | |
@Override public Statement apply(final Statement base, |
| 62 | |
FrameworkMethod method, Object target) { |
| 63 | 32 | return new Statement() { |
| 64 | |
@Override public void evaluate() throws Throwable { |
| 65 | 32 | inRuleContext = true; |
| 66 | 32 | base.evaluate(); |
| 67 | 30 | inRuleContext = false; |
| 68 | 30 | if (!gatherer.messages.isEmpty()) { |
| 69 | 5 | StringBuilder message = new StringBuilder("All failed expectations:\n"); |
| 70 | 12 | for (int i = 0; i < gatherer.messages.size(); i++) { |
| 71 | 7 | message.append(" ").append(i + 1).append(". ") |
| 72 | |
.append(gatherer.messages.get(i)).append("\n"); |
| 73 | |
} |
| 74 | 5 | throw new AssertionError(message.toString()); |
| 75 | |
} |
| 76 | 25 | } |
| 77 | |
}; |
| 78 | |
} |
| 79 | |
} |