How to use RecordState class of org.easymock.internal package

Best Easymock code snippet using org.easymock.internal.RecordState

Run Easymock automation tests on LambdaTest cloud grid

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

copy
1/*
2 * Copyright 2008,  Unitils.org
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.unitils.easymock.util;
17
18import java.util.List;
19
20import org.easymock.IAnswer;
21import org.easymock.IArgumentMatcher;
22import org.easymock.internal.IMocksControlState;
23import org.easymock.internal.Invocation;
24import org.easymock.internal.LastControl;
25import org.easymock.internal.MocksControl;
26import org.easymock.internal.Range;
27import org.easymock.internal.RecordState;
28import org.unitils.reflectionassert.ReflectionComparatorMode;
29
30/**
31 * An EasyMock mock control that uses the reflection argument matcher for all arguments of a method invocation.
32 * <p/>
33 * No explicit argument matcher setting is needed (or allowed). This control will automatically report
34 * lenient reflection argument matchers. These matchers can apply some leniency when comparing expected and actual
35 * argument values.
36 * <p/>
37 * Setting the {@link ReflectionComparatorMode#IGNORE_DEFAULTS} mode will for example ignore all fields that
38 * have default values as expected values. E.g. if a null value is recorded as argument it will not be checked when
39 * the actual invocation occurs. The same applies for inner-fields of object arguments that contain default java values.
40 * <p/>
41 * Setting the {@link ReflectionComparatorMode#LENIENT_DATES} mode will ignore the actual date values of arguments and
42 * inner fields of arguments. It will only check whether both dates are null or both dates are not null. The actual
43 * date and hour do not matter.
44 * <p/>
45 * Setting the {@link ReflectionComparatorMode#LENIENT_ORDER} mode will ignore the actual order of collections and
46 * arrays arguments and inner fields of arguments. It will only check whether they both contain the same elements.
47 *
48 * @author Tim Ducheyne
49 * @author Filip Neven
50 * @see ReflectionComparatorMode
51 * @see org.unitils.reflectionassert.ReflectionComparator
52 */
53public class LenientMocksControl extends MocksControl {
54
55
56    /***/
57    private static final long serialVersionUID = -4612378998272988410L;
58    /* The interceptor that wraps the record state */
59    private InvocationInterceptor invocationInterceptor;
60
61
62    /**
63     * Creates a default (no default returns and no order checking) mock control.
64     *
65     * @param modes the modes for the reflection argument matcher
66     */
67    public LenientMocksControl(ReflectionComparatorMode... modes) {
68        this(org.easymock.MockType.DEFAULT, modes);
69    }
70
71
72    /**
73     * Creates a mock control.<ul>
74     * <li>Default mock type: no default return values and no order checking</li>
75     * <li>Nice mock type: returns default values if no return value set, no order checking</li>
76     * <li>Strict mock type: no default return values and strict order checking</li>
77     * </ul>
78     *
79     * @param type  the EasyMock mock type
80     * @param modes the modes for the reflection argument matcher
81     */
82    public LenientMocksControl(org.easymock.MockType type, ReflectionComparatorMode... modes) {
83        super(type);
84        this.invocationInterceptor = new InvocationInterceptor(modes);
85    }
86
87
88    /**
89     * Overriden to be able to replace the record behavior that going to record all method invocations.
90     * The interceptor will make sure that reflection argument matchers will be reported for the
91     * arguments of all recorded method invocations.
92     *
93     * @return the state, wrapped in case of a RecordState
94     */
95    @Override
96    public IMocksControlState getState() {
97        IMocksControlState mocksControlState = super.getState();
98        if (mocksControlState instanceof RecordState) {
99            invocationInterceptor.setRecordState((RecordState) mocksControlState);
100            return invocationInterceptor;
101        }
102        return mocksControlState;
103    }
104
105
106    /**
107     * A wrapper for the record state in easy mock that will intercept the invoke method
108     * so that it can install reflection argument matchers for all arguments of the recorded method invocation.
109     * <p/>
110     * The old easy mock way of having a single argument matcher for all arguments has been deprecated. Since
111     * EasyMock 2 each argument should have its own matcher. We however want to avoid having to set all
112     * matchers to the reflection argument matcher explicitly.
113     * Because some of the methods are declared final and some classes explicitly cast to subtypes, creating a wrapper
114     * seems to be the only way to be able to intercept the matcher behavior.
115     */
116    private class InvocationInterceptor implements IMocksControlState {
117
118        /* The wrapped record state */
119        private RecordState recordState;
120
121        /* The modes for the reflection argument matchers */
122        private ReflectionComparatorMode[] modes;
123
124
125        /**
126         * Creates an interceptor that will create reflection argument matchers for all arguments of all recorded
127         * method invocations.
128         *
129         * @param modes the modes for the reflection argument matchers
130         */
131        public InvocationInterceptor(ReflectionComparatorMode... modes) {
132            this.modes = modes;
133        }
134
135
136        /**
137         * Sets the current wrapped record state.
138         *
139         * @param recordState the state, not null
140         */
141        public void setRecordState(RecordState recordState) {
142            this.recordState = recordState;
143        }
144
145
146        /**
147         * Overriden to report reflection argument matchers for all arguments of the given method invocation.
148         *
149         * @param invocation the method invocation, not null
150         * @return the result of the invocation
151         */
152        @Override
153        public Object invoke(Invocation invocation) {
154            LastControl.reportLastControl(LenientMocksControl.this);
155            createMatchers(invocation);
156            return recordState.invoke(invocation);
157        }
158
159
160        /**
161         * Reports report reflection argument matchers for all arguments of the given method invocation.
162         * An exception will be thrown if there were already matchers reported for the invocation.
163         *
164         * @param invocation the method invocation, not null
165         */
166        private void createMatchers(Invocation invocation) {
167            List<IArgumentMatcher> matchers = LastControl.pullMatchers();
168            if (matchers != null && !matchers.isEmpty()) {
169                if (matchers.size() != invocation.getArguments().length) {
170                    throw new IllegalStateException("This mock control does not support mixing of no-argument matchers and per-argument matchers. " +
171                            "Either no matchers are defined and the reflection argument matcher is used by default or all matchers are defined explicitly (Eg by using refEq()).");
172                }
173                // put all matchers back since pull removes them
174                for (IArgumentMatcher matcher : matchers) {
175                    LastControl.reportMatcher(matcher);
176                }
177                return;
178            }
179            Object[] arguments = invocation.getArguments();
180            if (arguments == null) {
181                return;
182            }
183
184            for (Object argument : arguments) {
185                LastControl.reportMatcher(new ReflectionArgumentMatcher<Object>(argument, modes));
186            }
187        }
188
189        // Pass through delegation
190
191        @Override
192        public void assertRecordState() {
193            recordState.assertRecordState();
194        }
195
196        @Override
197        public void andReturn(Object value) {
198            recordState.andReturn(value);
199        }
200
201        @Override
202        public void andThrow(Throwable throwable) {
203            recordState.andThrow(throwable);
204        }
205
206        @Override
207        public void andAnswer(IAnswer<?> answer) {
208            recordState.andAnswer(answer);
209        }
210
211        @Override
212        public void andStubReturn(Object value) {
213            recordState.andStubReturn(value);
214        }
215
216        @Override
217        public void andStubThrow(Throwable throwable) {
218            recordState.andStubThrow(throwable);
219        }
220
221        @Override
222        public void andStubAnswer(IAnswer<?> answer) {
223            recordState.andStubAnswer(answer);
224        }
225
226        @Override
227        public void asStub() {
228            recordState.asStub();
229        }
230
231        @Override
232        public void times(Range range) {
233            recordState.times(range);
234        }
235
236        @Override
237        public void checkOrder(boolean value) {
238            recordState.checkOrder(value);
239        }
240
241        @Override
242        public void replay() {
243            recordState.replay();
244        }
245
246        @Override
247        public void verify() {
248            recordState.verify();
249        }
250
251        /*public void setDefaultReturnValue(Object value) {
252            recordState.setDefaultReturnValue(value);
253        }
254
255        public void setDefaultThrowable(Throwable throwable) {
256            recordState.setDefaultThrowable(throwable);
257        }
258
259        public void setDefaultVoidCallable() {
260            recordState.setDefaultVoidCallable();
261        }
262
263        public void setDefaultMatcher(ArgumentsMatcher matcher) {
264            recordState.setDefaultMatcher(matcher);
265        }
266
267        public void setMatcher(Method method, ArgumentsMatcher matcher) {
268            recordState.setMatcher(method, matcher);
269        }*/
270
271
272        /**
273         * @see org.easymock.internal.IMocksControlState#andDelegateTo(java.lang.Object)
274         */
275        @Override
276        public void andDelegateTo(Object value) {
277            recordState.andDelegateTo(value);
278
279        }
280
281
282        /**
283         * @see org.easymock.internal.IMocksControlState#andStubDelegateTo(java.lang.Object)
284         */
285        @Override
286        public void andStubDelegateTo(Object value) {
287            recordState.andStubDelegateTo(value);
288
289        }
290
291
292        /**
293         * @see org.easymock.internal.IMocksControlState#checkIsUsedInOneThread(boolean)
294         */
295        @Override
296        public void checkIsUsedInOneThread(boolean value) {
297            recordState.checkIsUsedInOneThread(value);
298
299        }
300
301
302        /**
303         * @see org.easymock.internal.IMocksControlState#makeThreadSafe(boolean)
304         */
305        @Override
306        public void makeThreadSafe(boolean value) {
307            recordState.makeThreadSafe(value);
308
309        }
310    }
311
312}
313
Full Screen
copy
1/*
2 * Copyright 2011 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy of
6 * the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations under
14 * the License.
15 */
16
17package com.google.gwt.testing.easygwtmock.client.internal;
18
19import com.google.gwt.testing.easygwtmock.client.ArgumentMatcher;
20import com.google.gwt.testing.easygwtmock.client.internal.matchers.Any;
21import com.google.gwt.testing.easygwtmock.client.internal.matchers.ArgumentCapture;
22import com.google.gwt.testing.easygwtmock.client.internal.matchers.Equals;
23
24import junit.framework.TestCase;
25
26import org.easymock.EasyMock;
27
28import java.util.ArrayList;
29
30/**
31 * Tests the RecordState class
32 * 
33 * @author Michael Goderbauer
34 */
35public class RecordStateJavaTest extends TestCase {
36  
37  private MocksBehavior behavior;
38  private RecordState recordState;
39
40  @Override
41  public void setUp(){
42    behavior = EasyMock.createMock(MocksBehavior.class);
43    recordState = new RecordState(behavior);
44  }
45  
46  public void testVerify() {
47    EasyMock.replay(behavior);
48    try {
49      recordState.verify();
50    } catch (IllegalStateExceptionWrapper expected) {
51      assertEquals("Calling verify is not allowed in record state",
52          expected.getIllegalStateException().getMessage());
53    }
54    EasyMock.verify(behavior);
55  }
56  
57  public void testReportMatcher() {
58    EasyMock.replay(behavior);
59    
60    recordState.reportMatcher(Any.ANY);
61    assertEquals(1, recordState.argumentMatchers.size());
62    assertTrue(recordState.argumentMatchers.contains(Any.ANY));
63    
64    
65    ArgumentMatcher matcher = new Equals(3);
66    recordState.reportMatcher(matcher);
67    assertEquals(2, recordState.argumentMatchers.size());
68    assertTrue(recordState.argumentMatchers.contains(Any.ANY));
69    assertTrue(recordState.argumentMatchers.contains(matcher));
70    
71    EasyMock.verify(behavior);
72  }
73  
74  public void testReportCapture() throws IllegalStateExceptionWrapper {
75    EasyMock.replay(behavior);
76    
77    ArgumentCapture capture1 = EasyMock.createMock(ArgumentCapture.class);
78    ArgumentCapture capture2 = EasyMock.createMock(ArgumentCapture.class);
79    EasyMock.replay(capture1);
80    EasyMock.replay(capture2);
81    
82    recordState.reportCapture(capture1);
83    assertEquals(1, recordState.argumentCaptures.size());
84    assertTrue(recordState.argumentCaptures.contains(capture1));
85    
86    recordState.reportCapture(capture2);
87    assertEquals(2, recordState.argumentCaptures.size());
88    assertTrue(recordState.argumentCaptures.contains(capture1));
89    assertTrue(recordState.argumentCaptures.contains(capture2));
90    
91    EasyMock.verify(behavior);
92    EasyMock.verify(capture1);
93    EasyMock.verify(capture2);
94  }
95  
96  public void testReportCapture_SameTwice() throws IllegalStateExceptionWrapper {
97    EasyMock.replay(behavior);
98    
99    ArgumentCapture capture = EasyMock.createMock(ArgumentCapture.class);
100    EasyMock.replay(capture);
101    
102    recordState.reportCapture(capture);
103    
104    try {
105      recordState.reportCapture(capture);
106    } catch (IllegalStateExceptionWrapper expected) {
107    }
108    
109    EasyMock.verify(behavior);
110    EasyMock.verify(capture);
111  }
112  
113  public void testCheckCanSwitchToReplay_noCurrentSetter() {
114    EasyMock.replay(behavior);
115    
116    assertNull(recordState.currentSetter);
117    recordState.checkCanSwitchToReplay();
118    assertNull(recordState.currentSetter);
119    
120    EasyMock.verify(behavior);
121  }
122  
123  public void testCheckCanSwitchToReplay_withCurrentSetter() {
124    EasyMock.replay(behavior);
125    
126    ExpectationSettersImpl setter = EasyMock.createMock(ExpectationSettersImpl.class);
127    setter.retire();
128    EasyMock.replay(setter);
129    
130    recordState.currentSetter = setter;
131    recordState.checkCanSwitchToReplay();
132    assertNull(recordState.currentSetter);
133    
134    EasyMock.verify(setter);
135    EasyMock.verify(behavior);
136  }
137  
138  public void testGetExpectationSetter_noSetter() {
139    EasyMock.replay(behavior);
140    assertNull(recordState.currentSetter);
141    
142    try {
143      recordState.getExpectationSetter();
144    } catch (IllegalStateExceptionWrapper expected) {
145    }
146
147    EasyMock.verify(behavior);
148  }
149  
150  public void testGetExpectationSetter_withSetter() throws IllegalStateExceptionWrapper {
151    EasyMock.replay(behavior);
152    
153    ExpectationSettersImpl setter = EasyMock.createMock(ExpectationSettersImpl.class);
154    EasyMock.replay(setter);
155    
156    recordState.currentSetter = setter;
157    assertSame(setter, recordState.getExpectationSetter());
158    
159    EasyMock.verify(setter);
160    EasyMock.verify(behavior);
161  }
162  
163  public void testInvoke() throws Throwable {
164    EasyMock.replay(behavior);
165    Call call = EasyMock.createMock(Call.class);
166    EasyMock.expect(call.getDefaultReturnValue()).andReturn(0);
167    EasyMock.expect(call.getArguments()).andReturn(new ArrayList<Object>());
168    EasyMock.replay(call);
169    
170    ExpectationSettersImpl setter = recordState.currentSetter;
171    
172    assertEquals(0, recordState.invoke(call).answer(null));
173    assertNull(recordState.argumentCaptures);
174    assertNull(recordState.argumentMatchers);
175    assertNotNull(recordState.currentSetter);
176    assertNotSame(setter, recordState.currentSetter);
177    
178    EasyMock.verify(behavior);
179    EasyMock.verify(call);
180  }
181  
182  public void testInvoke_retirePrevious() {
183    EasyMock.replay(behavior);
184    Call call = EasyMock.createMock(Call.class);
185    EasyMock.expect(call.getDefaultReturnValue()).andReturn(0);
186    EasyMock.expect(call.getArguments()).andReturn(new ArrayList<Object>());
187    EasyMock.replay(call);
188    
189    ExpectationSettersImpl setter = EasyMock.createMock(ExpectationSettersImpl.class);
190    setter.retire();
191    EasyMock.replay(setter);
192    
193    recordState.currentSetter = setter;
194    
195    recordState.invoke(call);
196    assertNotSame(setter, recordState.currentSetter);
197    
198    EasyMock.verify(behavior);
199    EasyMock.verify(call);
200    EasyMock.verify(setter);
201  }
202}
203
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
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)