How to use method of org.jmock.test.unit.support.AssertThat class

Best Jmock-library code snippet using org.jmock.test.unit.support.AssertThat.

Run Jmock-library automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1/*  Copyright (c) 2000-20047 jMock.org
2 */
3package org.jmock.test.unit.lib.action;
4
5import java.lang.reflect.Method;
6
7import junit.framework.TestCase;
8
9import org.hamcrest.StringDescription;
10import org.jmock.api.Action;
11import org.jmock.api.ExpectationError;
12import org.jmock.api.Invocation;
13import org.jmock.lib.action.ActionSequence;
14import org.jmock.test.unit.support.AssertThat;
15import org.jmock.test.unit.support.MethodFactory;
16import org.jmock.test.unit.support.MockAction;
17
18
19public class ActionSequenceTests extends TestCase {
20    private Object invokedObject = "INVOKED_OBJECT";
21    private MethodFactory methodFactory = new MethodFactory();
22    private Method invokedMethod = methodFactory.newMethodReturning(String.class);
23    private Invocation invocation = new Invocation(invokedObject, invokedMethod);
24    
25    
26    @SuppressWarnings("cast") // Eclipse gives warning if there is a cast and if there is not!
27    public void testInvokesActionsInOrder() throws Throwable {
28    	final int sequenceLength = 4;
29    	
30        MockAction[] actions = new MockAction[sequenceLength];        
31        for (int i = 0; i < sequenceLength; i++) {
32            actions[i] = new MockAction();
33            actions[i].result = "RESULT-" + i;
34            if (i > 0) actions[i].previous = actions[i-1];
35        }
36        
37        Invocation[] invocations = new Invocation[actions.length];
38        for (int i = 0; i < sequenceLength; i++) {
39        	invocations[i] = new Invocation(invokedObject, invokedMethod);
40        }
41        
42        ActionSequence sequence = new ActionSequence((Action[])actions);
43        
44        for (int current = 0; current < actions.length; current++) {
45            reset(actions);
46            actions[current].expectInvoke = true;
47            actions[current].expectedInvocation = invocation;
48            
49            Object result = sequence.invoke(invocation);
50            
51			assertSame("should be result of actions[" + current + "]",
52                         actions[current].result, result);
53        }
54    }
55    
56    @SuppressWarnings("cast") // Eclipse gives warning if there is a cast and if there is not!
57    public void testFailsIfInvokedMoreTimesThanThereAreActionsInTheSequence() throws Throwable {
58        MockAction[] actions = new MockAction[]{new MockAction(), new MockAction()};
59        ActionSequence sequence = new ActionSequence((Action[])actions);
60        
61        for (int i = 0; i < actions.length; i++) sequence.invoke(invocation);
62        
63        try {
64            sequence.invoke(invocation);
65            fail("should have thrown IllegalStateException");
66        }
67        catch (ExpectationError ex) {
68            AssertThat.stringIncludes("should describe error",
69                "no more actions", ex.getMessage());
70            return;
71        }
72    }
73    
74    @SuppressWarnings("cast") // Eclipse gives warning if there is a cast and if there is not!
75    public void testDescribesItselfAsSequenceOfActions() throws Throwable {
76        MockAction[] actions = new MockAction[]{new MockAction(), new MockAction()};
77        ActionSequence sequence = new ActionSequence((Action[])actions);
78        
79        String sequenceDescription = StringDescription.toString(sequence);
80
81        for (int i = 0; i < actions.length; i++) {
82            AssertThat.stringIncludes("should include action " + i,
83                actions[i].descriptionText, sequenceDescription);
84
85            if (i > 0) {
86                int h = i - 1;
87                
88                assertTrue("description of action " + h + " should be before that of action " + i,
89                           sequenceDescription.indexOf(actions[h].descriptionText) <
90                           sequenceDescription.indexOf(actions[i].descriptionText));
91            }
92        }
93    }
94
95    private void reset( MockAction[] actions ) {
96        for (int i = 0; i < actions.length; i++) {
97            actions[i].expectInvoke = false;
98        }
99    }
100}
101
Full Screen
copy
1package org.jmock.test.unit.internal;
2
3import static org.hamcrest.Matchers.equalTo;
4import static org.hamcrest.Matchers.sameInstance;
5
6import java.lang.reflect.Method;
7
8import junit.framework.TestCase;
9
10import org.hamcrest.BaseMatcher;
11import org.hamcrest.Description;
12import org.hamcrest.Matcher;
13import org.hamcrest.StringDescription;
14import org.jmock.api.Invocation;
15import org.jmock.internal.Cardinality;
16import org.jmock.internal.InvocationExpectation;
17import org.jmock.internal.OrderingConstraint;
18import org.jmock.internal.SideEffect;
19import org.jmock.internal.matcher.AllParametersMatcher;
20import org.jmock.lib.action.ReturnValueAction;
21import org.jmock.test.unit.support.AssertThat;
22import org.jmock.test.unit.support.MethodFactory;
23import org.jmock.test.unit.support.MockAction;
24
25public class InvocationExpectationTests extends TestCase {
26	MethodFactory methodFactory = new MethodFactory();
27	InvocationExpectation expectation = new InvocationExpectation();
28	Object targetObject = "targetObject";
29	Method method = methodFactory.newMethod("method");
30	
31	public <T> Matcher<T> mockMatcher(final T expected, final boolean result) {
32		return new BaseMatcher<T>() {
33			public boolean matches(Object actual) {
34				assertTrue("expected " + expected + ", was " + actual,
35				           equalTo(expected).matches(actual));
36				return result;
37			}
38			public void describeTo(Description description) {
39			}
40		};
41	}
42	
43	public void testMatchesAnythingByDefault() {
44		assertTrue("should match", expectation.matches(
45				new Invocation(new Object(), methodFactory.newMethod("method"), Invocation.NO_PARAMETERS)));
46
47		assertTrue("should match", expectation.matches(
48				new Invocation(new Object(), methodFactory.newMethod("anotherMethod"), 
49						       new Object[]{1,2,3,4})));
50	}
51	
52	public void testCanConstrainTargetObject() {
53		Object anotherObject = "anotherObject";
54		
55		expectation.setObjectMatcher(sameInstance(targetObject));
56		
57		assertTrue("should match", expectation.matches(new Invocation(targetObject, method, Invocation.NO_PARAMETERS)));
58		assertTrue("should not match", !expectation.matches(new Invocation(anotherObject, method, Invocation.NO_PARAMETERS)));
59	}
60	
61	public void testCanConstrainMethod() {
62		Method anotherMethod = methodFactory.newMethod("anotherMethod");
63		
64		expectation.setMethodMatcher(equalTo(method));
65		
66		assertTrue("should match", expectation.matches(new Invocation(targetObject, method, Invocation.NO_PARAMETERS)));
67		assertTrue("should not match", !expectation.matches(new Invocation(targetObject, anotherMethod, Invocation.NO_PARAMETERS)));
68	}
69	
70	public void testCanConstrainArguments() {
71		Object[] args = {1,2,3,4};
72		Object[] differentArgs = {5,6,7,8};
73		Object[] differentArgCount = {1,2,3};
74		Object[] noArgs = null;
75		
76		expectation.setParametersMatcher(new AllParametersMatcher(args));
77		
78		assertTrue("should match", expectation.matches(new Invocation(targetObject, method, args)));
79		assertTrue("should not match", !expectation.matches(new Invocation(targetObject, method, differentArgs)));
80		assertTrue("should not match", !expectation.matches(new Invocation(targetObject, method, differentArgCount)));
81		assertTrue("should not match", !expectation.matches(new Invocation(targetObject, method, noArgs)));
82	}
83	
84	public void testDoesNotMatchIfMatchingCountMatcherDoesNotMatch() throws Throwable {
85		Invocation invocation = new Invocation("targetObject", methodFactory.newMethod("method"), Invocation.NO_PARAMETERS);
86		
87		int maxInvocationCount = 3;
88        
89        expectation.setCardinality(new Cardinality(0, maxInvocationCount));
90		
91		int i;
92		for (i = 0; i < maxInvocationCount; i++) {
93			assertTrue("should match after " + i +" invocations", expectation.matches(invocation));
94			expectation.invoke(invocation);
95		}
96		assertFalse("should not match after " + i + " invocations", expectation.matches(invocation));
97	}
98	
99	public void testMustMeetTheRequiredInvocationCountButContinuesToMatch() throws Throwable {
100		Invocation invocation = new Invocation("targetObject", methodFactory.newMethod("method"));
101		
102		int requiredInvocationCount = 3;
103		expectation.setCardinality(new Cardinality(requiredInvocationCount, Integer.MAX_VALUE));
104		
105		int i;
106		for (i = 0; i < requiredInvocationCount; i++) {
107			assertTrue("should match after " + i +" invocations", 
108					expectation.matches(invocation));
109			assertFalse("should not be satisfied after " + i +" invocations",
110					expectation.isSatisfied());
111			
112			expectation.invoke(invocation);
113		}
114
115		assertTrue("should match after " + i +" invocations", 
116		           expectation.matches(invocation));
117		assertTrue("should be satisfied after " + i +" invocations",
118		           expectation.isSatisfied());
119	}
120
121    public void testPerformsActionWhenInvoked() throws Throwable {
122        final Method stringReturningMethod = methodFactory.newMethod("tester", new Class[0], String.class, new Class[0]);
123        Invocation invocation = new Invocation(targetObject, stringReturningMethod, Invocation.NO_PARAMETERS);
124        MockAction action = new MockAction();
125        
126        action.expectInvoke = true;
127        action.expectedInvocation = invocation;
128        action.result = "result";
129        
130        expectation.setAction(action);
131        
132        Object actualResult = expectation.invoke(invocation);
133        
134        assertSame("actual result", action.result, actualResult);
135        assertTrue("action1 was invoked", action.wasInvoked);
136    }
137    
138    public void testPerformsSideEffectsWhenInvoked() throws Throwable {
139        FakeSideEffect sideEffect1 = new FakeSideEffect();
140        FakeSideEffect sideEffect2 = new FakeSideEffect();
141        
142        expectation.addSideEffect(sideEffect1);
143        expectation.addSideEffect(sideEffect2);
144        
145        Invocation invocation = new Invocation("targetObject", methodFactory.newMethod("method"));
146        expectation.invoke(invocation);
147        
148        assertTrue("side effect 1 should have been performed", sideEffect1.wasPerformed);
149        assertTrue("side effect 2 should have been performed", sideEffect2.wasPerformed);
150    }
151    
152    public void testDescriptionIncludesSideEffects() {
153        FakeSideEffect sideEffect1 = new FakeSideEffect();
154        FakeSideEffect sideEffect2 = new FakeSideEffect();
155        
156        sideEffect1.descriptionText = "side-effect-1";
157        sideEffect2.descriptionText = "side-effect-2";
158        
159        expectation.addSideEffect(sideEffect1);
160        expectation.addSideEffect(sideEffect2);
161        
162        String description = StringDescription.toString(expectation);
163        
164        AssertThat.stringIncludes("should include description of sideEffect1",
165                                  sideEffect1.descriptionText, description);
166        AssertThat.stringIncludes("should include description of sideEffect2",
167                                  sideEffect2.descriptionText, description);
168        
169    }
170    
171    public void testReturnsNullIfHasNoActionsWhenInvoked() throws Throwable {
172        Invocation invocation = new Invocation(targetObject, method, Invocation.NO_PARAMETERS);
173        
174        Object actualResult = expectation.invoke(invocation);
175        
176        assertNull("should have returned null", actualResult);
177    }
178    
179
180    public void testFailsIfActionReturnsAnIncompatibleValue() throws Throwable {
181        final Method stringReturningMethod = methodFactory.newMethod("tester", new Class[0], String.class, new Class[0]);
182        Invocation invocation = new Invocation(targetObject, stringReturningMethod, Invocation.NO_PARAMETERS);
183        ReturnValueAction action = new ReturnValueAction(new Integer(666));
184        expectation.setAction(action);
185        
186        try {
187            expectation.invoke(invocation);
188            fail("Should have thrown an IllegalStateException");
189        } catch (IllegalStateException expected) {
190            AssertThat.stringIncludes("Shows returned type", "java.lang.Integer", expected.getMessage());
191            AssertThat.stringIncludes("Shows expected return type", "java.lang.String", expected.getMessage());
192        }
193    }
194    
195    /**
196     * @see CardinalityTests.testHasARequiredAndMaximumNumberOfExpectedInvocations
197     */
198    public void testHasARequiredAndMaximumNumberOfExpectedInvocations() throws Throwable {
199        Invocation invocation = new Invocation(targetObject, method, Invocation.NO_PARAMETERS);
200        
201        expectation.setCardinality(new Cardinality(1, 1));
202        
203        assertTrue(expectation.allowsMoreInvocations());
204        assertFalse(expectation.isSatisfied());
205        
206        expectation.invoke(invocation);
207        expectation.invoke(invocation);
208        
209        assertFalse(expectation.allowsMoreInvocations());
210        assertTrue(expectation.isSatisfied());
211    }
212    
213    public void testMatchesIfAllOrderingConstraintsMatch() {
214        FakeOrderingConstraint orderingConstraint1 = new FakeOrderingConstraint();
215        FakeOrderingConstraint orderingConstraint2 = new FakeOrderingConstraint();
216        
217        expectation.addOrderingConstraint(orderingConstraint1);
218        expectation.addOrderingConstraint(orderingConstraint2);
219        
220        Invocation invocation = new Invocation(targetObject, method, Invocation.NO_PARAMETERS);
221        
222        orderingConstraint1.allowsInvocationNow = true;
223        orderingConstraint2.allowsInvocationNow = true;
224        assertTrue(expectation.matches(invocation));
225        
226        orderingConstraint1.allowsInvocationNow = true;
227        orderingConstraint2.allowsInvocationNow = false;
228        assertFalse(expectation.matches(invocation));
229        
230        orderingConstraint1.allowsInvocationNow = false;
231        orderingConstraint2.allowsInvocationNow = true;
232        assertFalse(expectation.matches(invocation));
233        
234        orderingConstraint1.allowsInvocationNow = false;
235        orderingConstraint2.allowsInvocationNow = false;
236        assertFalse(expectation.matches(invocation));
237    }
238    
239    public void testDescriptionIncludesCardinality() {
240        final Cardinality cardinality = new Cardinality(2, 2);
241        expectation.setCardinality(cardinality);
242        
243        AssertThat.stringIncludes("should include cardinality description",
244                                  StringDescription.toString(cardinality), 
245                                  StringDescription.toString(expectation));
246    }
247    
248    public void testDescribesNumberOfInvocationsReceived() throws Throwable {
249        Invocation invocation = new Invocation(targetObject, method, Invocation.NO_PARAMETERS);
250        
251        expectation.setCardinality(new Cardinality(2,3));
252        
253        AssertThat.stringIncludes("should describe as not invoked",
254                                  "never invoked", StringDescription.toString(expectation));
255        
256        expectation.invoke(invocation);
257        AssertThat.stringIncludes("should describe as not invoked",
258                                  "invoked 1 time", StringDescription.toString(expectation));
259        
260        expectation.invoke(invocation);
261        expectation.invoke(invocation);
262        AssertThat.stringIncludes("should describe as not invoked",
263                                  "invoked 3 times", StringDescription.toString(expectation));
264    }
265
266    public static class FakeOrderingConstraint implements OrderingConstraint {
267        public boolean allowsInvocationNow;
268        
269        public boolean allowsInvocationNow() {
270            return allowsInvocationNow;
271        }
272
273        public String descriptionText;
274        
275        public void describeTo(Description description) {
276            description.appendText(descriptionText);
277        }
278    }
279    
280    class FakeSideEffect implements SideEffect {
281        public boolean wasPerformed = false;
282        
283        public void perform() {
284            wasPerformed = true;
285        }
286
287        public String descriptionText;
288        
289        public void describeTo(Description description) {
290            description.appendText(descriptionText);
291        }
292    }
293}
294
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Trigger code on LambdaTest Cloud Grid

Execute automation tests with on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)