| 1 |
package org.jmock.integration.junit4; |
| 2 |
|
| 3 |
import org.jmock.auto.internal.Mockomatic; |
| 4 |
import org.jmock.internal.AllDeclaredFields; |
| 5 |
import org.junit.rules.MethodRule; |
| 6 |
import org.junit.runners.model.FrameworkMethod; |
| 7 |
import org.junit.runners.model.Statement; |
| 8 |
|
| 9 |
import java.lang.reflect.Field; |
| 10 |
import java.util.List; |
| 11 |
|
| 12 |
import static org.junit.Assert.fail; |
| 13 |
|
| 14 |
/** |
| 15 |
* A <code>JUnitRuleMockery</code> is a JUnit Rule that manages JMock expectations |
| 16 |
* and allowances, and asserts that expectations have been met after each test |
| 17 |
* has finished. To use it, add a field to the test class (note that you don't |
| 18 |
* have to specify <code>@RunWith(JMock.class)</code> any more). For example, |
| 19 |
* |
| 20 |
* <pre>public class ATestWithSatisfiedExpectations { |
| 21 |
* @Rule public final JUnitRuleMockery context = new JUnitRuleMockery(); |
| 22 |
* private final Runnable runnable = context.mock(Runnable.class); |
| 23 |
* |
| 24 |
* @Test |
| 25 |
* public void doesSatisfyExpectations() { |
| 26 |
* context.checking(new Expectations() {{ |
| 27 |
* oneOf (runnable).run(); |
| 28 |
* }}); |
| 29 |
* |
| 30 |
* runnable.run(); |
| 31 |
* } |
| 32 |
*}</pre> |
| 33 |
* |
| 34 |
* Note that the Rule field must be declared public and as a <code>JUnitRuleMockery</code> |
| 35 |
* (not a <code>Mockery</code>) for JUnit to recognise it, as it's checked statically. |
| 36 |
* @author smgf |
| 37 |
*/ |
| 38 |
|
| 39 |
public class JUnitRuleMockery extends JUnit4Mockery implements MethodRule { |
| 40 |
private final Mockomatic mockomatic = new Mockomatic(this); |
| 41 |
|
| 42 |
public Statement apply(final Statement base, FrameworkMethod method, final Object target) { |
| 43 |
return new Statement() { |
| 44 |
@Override |
| 45 |
public void evaluate() throws Throwable { |
| 46 |
prepare(target); |
| 47 |
base.evaluate(); |
| 48 |
assertIsSatisfied(); |
| 49 |
} |
| 50 |
|
| 51 |
private void prepare(final Object target) { |
| 52 |
List<Field> allFields = AllDeclaredFields.in(target.getClass()); |
| 53 |
assertOnlyOneJMockContextIn(allFields); |
| 54 |
fillInAutoMocks(target, allFields); |
| 55 |
} |
| 56 |
|
| 57 |
private void assertOnlyOneJMockContextIn(List<Field> allFields) { |
| 58 |
Field contextField = null; |
| 59 |
for (Field field : allFields) { |
| 60 |
if (JUnitRuleMockery.class.isAssignableFrom(field.getType())) { |
| 61 |
if (null != contextField) { |
| 62 |
fail("Test class should only have one JUnitRuleMockery field, found " |
| 63 |
+ contextField.getName() + " and " + field.getName()); |
| 64 |
} |
| 65 |
contextField = field; |
| 66 |
} |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
private void fillInAutoMocks(final Object target, List<Field> allFields) { |
| 71 |
mockomatic.fillIn(target, allFields); |
| 72 |
} |
| 73 |
}; |
| 74 |
} |
| 75 |
} |