Debian Codegraph @

jmock-junit4/src/main/java/org/jmock/integration/junit4/JMock.java

raw
1 package org.jmock.integration.junit4;
2
3 import org.jmock.Mockery;
4 import org.jmock.auto.internal.Mockomatic;
5 import org.jmock.internal.AllDeclaredFields;
6 import org.junit.runner.Runner;
7 import org.junit.runners.BlockJUnit4ClassRunner;
8 import org.junit.runners.model.FrameworkMethod;
9 import org.junit.runners.model.InitializationError;
10 import org.junit.runners.model.Statement;
11
12 import java.lang.reflect.Field;
13
14
15 /**
16 * A test {@link Runner} that asserts that all expectations have been met after
17 * the test has finished and before the fixture is torn down.
18 * @deprecated For JUnit 4 use {@link JUnitRuleMockery}
19 * @author nat steve.freeman
20 *
21 */
22 @Deprecated
23 public class JMock extends BlockJUnit4ClassRunner {
24 private Field mockeryField;
25
26 public JMock(Class<?> testClass) throws InitializationError {
27 super(testClass);
28 mockeryField = findMockeryField(testClass);
29 mockeryField.setAccessible(true);
30 }
31
32 @Override
33 protected Object createTest() throws Exception {
34 Object test = super.createTest();
35 Mockomatic mockomatic = new Mockomatic(mockeryOf(test));
36 mockomatic.fillIn(test);
37 return test;
38 }
39
40 @Override @Deprecated
41 protected Statement possiblyExpectingExceptions(FrameworkMethod method, Object test, Statement next) {
42 return verify(method, test, super.possiblyExpectingExceptions(method, test, next));
43 }
44
45 protected Statement verify(
46 @SuppressWarnings("unused") FrameworkMethod method,
47 final Object test,
48 final Statement next)
49 {
50 return new Statement() {
51 @Override
52 public void evaluate() throws Throwable {
53 next.evaluate();
54 assertMockeryIsSatisfied(test);
55 }
56 };
57 }
58
59 protected void assertMockeryIsSatisfied(Object test) {
60 mockeryOf(test).assertIsSatisfied();
61 }
62
63 protected Mockery mockeryOf(Object test) {
64 try {
65 Mockery mockery = (Mockery)mockeryField.get(test);
66 if (mockery == null) {
67 throw new IllegalStateException("Mockery named '" + mockeryField.getName() + "' is null");
68 }
69 return mockery;
70 }
71 catch (IllegalAccessException e) {
72 throw new IllegalStateException("cannot get value of field " + mockeryField.getName(), e);
73 }
74 }
75
76 static Field findMockeryField(Class<?> testClass) throws InitializationError {
77 Field mockeryField = null;
78
79 for (Field field : AllDeclaredFields.in(testClass)) {
80 if (Mockery.class.isAssignableFrom(field.getType())) {
81 if (mockeryField != null) {
82 throw new InitializationError("more than one Mockery found in test class " + testClass);
83 }
84 mockeryField = field;
85 }
86 }
87
88 if (mockeryField == null) {
89 throw new InitializationError("no Mockery found in test class " + testClass);
90 }
91
92 return mockeryField;
93 }
94 }