How to use method of org.easymock.internal.MocksControl class

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

Run Easymock automation tests on LambdaTest cloud grid

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

copy
1/*
2 * Copyright 2008 Sanjiv Sahayam
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 com.googlecode.pondskum.gui.swing.notifyer.tray;
17
18import com.googlecode.pondskum.client.BigpondAccountInformation;
19import com.googlecode.pondskum.client.BigpondUsage;
20import com.googlecode.pondskum.client.BigpondUsageInformation;
21import org.easymock.EasyMock;
22import org.easymock.internal.MocksControl;
23import org.junit.Before;
24import org.junit.Test;
25
26import static org.hamcrest.core.IsEqual.equalTo;
27import static org.junit.Assert.assertThat;
28
29public final class UsageFormatterUnderTest {
30
31    private UsageFormatter usageFormatter;
32    private MocksControl mocksControl;
33    private QuotaFormatter mockQuotaFormatter;
34
35    @Before
36    public void setup() {
37        mocksControl = new MocksControl(MocksControl.MockType.DEFAULT);
38        mockQuotaFormatter = mocksControl.createMock(QuotaFormatter.class);
39        usageFormatter = new UsageFormatter(mockQuotaFormatter);
40    }
41
42    @Test public void shouldReturnAFormattedStringForValidData() {
43        BigpondUsageInformation mockBigpondUsageInformation = mocksControl.createMock(BigpondUsageInformation.class);
44        BigpondAccountInformation mockBigpondAccountInformation = mocksControl.createMock(BigpondAccountInformation.class);
45        BigpondUsage mockTotalUsage = mocksControl.createMock(BigpondUsage.class);
46
47        expectAccountInfo(mockBigpondUsageInformation, mockBigpondAccountInformation);
48        expectUsageInfo(mockBigpondUsageInformation, mockTotalUsage);
49        mocksControl.replay();
50
51        final String formattedUsage = usageFormatter.formatUsage(mockBigpondUsageInformation);
52        assertThat(formattedUsage, equalTo("Mr. Josh Pyke - ([U]1.24 GB | [D]6.58 GB | [T]7.89 GB)"));
53
54        mocksControl.verify();
55    }
56
57    @Test public void shouldReturnAFormattedStringForInvalidData() {
58        final String formattedUsage = usageFormatter.formatUsage(null);
59        assertThat(formattedUsage, equalTo("(Bigpond usage information is unavailable at the moment.)"));
60    }
61
62    private void expectUsageInfo(final BigpondUsageInformation mockBigpondUsageInformation, final BigpondUsage mockTotalUsage) {
63        EasyMock.expect(mockBigpondUsageInformation.getTotalUsage()).andReturn(mockTotalUsage);
64        EasyMock.expect(mockTotalUsage.getDownloadUsage()).andReturn("6578");
65        EasyMock.expect(mockTotalUsage.getUploadUsage()).andReturn("1236");
66        EasyMock.expect(mockTotalUsage.getTotalUsage()).andReturn("7893");
67        EasyMock.expect(mockQuotaFormatter.formatQuota("6578")).andReturn("6.58 GB");
68        EasyMock.expect(mockQuotaFormatter.formatQuota("1236")).andReturn("1.24 GB");
69        EasyMock.expect(mockQuotaFormatter.formatQuota("7893")).andReturn("7.89 GB");
70    }
71
72    private void expectAccountInfo(final BigpondUsageInformation mockBigpondUsageInformation,
73                                   final BigpondAccountInformation mockBigpondAccountInformation) {
74        EasyMock.expect(mockBigpondUsageInformation.getAccountInformation()).andReturn(mockBigpondAccountInformation);
75        EasyMock.expect(mockBigpondAccountInformation.getAccountName()).andReturn("Mr. Josh Pyke");
76    }
77}
78
Full Screen
copy
1package com.babeeta.hudee.core.rpc;
2
3import static org.easymock.EasyMock.capture;
4import static org.easymock.EasyMock.createControl;
5import static org.easymock.EasyMock.expect;
6import static org.easymock.EasyMock.expectLastCall;
7import static org.easymock.EasyMock.same;
8import static org.junit.Assert.assertFalse;
9import static org.junit.Assert.assertSame;
10import static org.junit.Assert.assertTrue;
11
12import java.util.Map;
13import java.util.concurrent.ScheduledFuture;
14import java.util.concurrent.TimeoutException;
15
16import org.easymock.Capture;
17import org.easymock.IAnswer;
18import org.easymock.IMocksControl;
19import org.junit.Before;
20import org.junit.Test;
21import org.springframework.test.util.ReflectionTestUtils;
22
23import com.babeeta.hudee.core.MessageFuture;
24import com.babeeta.hudee.core.MessageFutureListener;
25import com.babeeta.hudee.core.MessageRouting.Message;
26import com.babeeta.hudee.core.MessageSender;
27import com.google.protobuf.ByteString;
28
29@SuppressWarnings("javadoc")
30public class MessageBasedRPCServiceTest {
31
32	private MessageBasedRPCService service;
33	private MessageSender messageSender;
34	private MessageFuture messageFuture;
35	private IMocksControl mocksControl;
36	private ScheduledFuture<?> scheduledFuture;
37
38	@Before
39	public void setUp() throws Exception {
40		mocksControl = createControl();
41		messageFuture = mocksControl.createMock(MessageFuture.class);
42		messageSender = mocksControl.createMock(MessageSender.class);
43		service = new MessageBasedRPCService(messageSender);
44		scheduledFuture = mocksControl.createMock(ScheduledFuture.class);
45	}
46
47	@Test
48	public void testInvoke() {
49		Message call = Message.newBuilder()
50		        .setUid(String.valueOf(System.currentTimeMillis()))
51		        .setDate(System.currentTimeMillis())
52		        .setContent(ByteString.copyFrom(new byte[0]))
53		        .setFrom("From")
54		        .setTo("TO")
55		        .build();
56
57		Capture<MessageFutureListener> capture = new Capture<MessageFutureListener>();
58		RPCHandler handler = mocksControl.createMock(RPCHandler.class);
59
60		expect(messageSender.send(call))
61		        .andReturn(messageFuture)
62		        .once();
63		expect(messageFuture.addListener(capture(capture)))
64		        .andReturn(messageFuture)
65		        .once();
66		expect(messageFuture.isSuccess())
67		        .andReturn(true).once();
68		expect(messageFuture.isSuccess())
69		        .andReturn(false).atLeastOnce();
70		final Exception e = new Exception();
71		expect(messageFuture.getCause())
72		        .andReturn(e)
73		        .atLeastOnce();
74
75		handler.exceptionCaught(same(call), same(e));
76		expectLastCall().once();
77
78		handler.exceptionCaught(call, e);
79		expectLastCall().andThrow(new RuntimeException("Test."))
80		        .once();
81
82		mocksControl.replay();
83		service.invoke(call, handler);
84
85		@SuppressWarnings("unchecked")
86		Map<String, RPCInvoke> internalMap = (Map<String, RPCInvoke>) ReflectionTestUtils
87		        .getField(service, "rpcRegistry");
88
89		assertTrue(capture.hasCaptured());
90		assertTrue(internalMap.containsKey(call.getUid()));
91
92		capture.getValue().operationComplete(messageFuture);
93		assertTrue(internalMap.containsKey(call.getUid()));
94		assertSame(internalMap.get(call.getUid()).handler, handler);
95
96		internalMap.clear();
97		capture.getValue().operationComplete(messageFuture);
98		assertFalse(internalMap.containsKey(call.getUid()));
99
100		capture.getValue().operationComplete(messageFuture);
101		assertFalse(internalMap.containsKey(call.getUid()));
102	}
103
104	@Test
105	public void testInvoke超时后会被清除掉() throws InterruptedException {
106		Message call = Message.newBuilder()
107		        .setUid(String.valueOf(System.currentTimeMillis()))
108		        .setDate(System.currentTimeMillis())
109		        .setContent(ByteString.copyFrom(new byte[0]))
110		        .setFrom("From")
111		        .setTo("TO")
112		        .build();
113
114		final Capture<MessageFutureListener> capture = new Capture<MessageFutureListener>();
115		RPCHandler handler = mocksControl.createMock(RPCHandler.class);
116
117		expect(messageSender.send(call))
118		        .andReturn(messageFuture)
119		        .once();
120		expect(messageFuture.addListener(capture(capture)))
121		        .andAnswer(new IAnswer<MessageFuture>() {
122
123			        @Override
124			        public MessageFuture answer() throws Throwable {
125				        capture.getValue().operationComplete(messageFuture);
126				        return messageFuture;
127			        }
128		        }).once();
129		expect(messageFuture.isSuccess())
130		        .andReturn(true).once();
131
132		Capture<Throwable> throwableCapture = new Capture<Throwable>();
133		handler.exceptionCaught(same(call), capture(throwableCapture));
134		expectLastCall().once();
135
136		mocksControl.replay();
137
138		service.invokeTimeout = 1;
139
140		service.invoke(call, handler);
141		Thread.sleep(1020L);
142
143		assertTrue(throwableCapture.hasCaptured());
144		assertTrue(throwableCapture.getValue() instanceof TimeoutException);
145	}
146
147	@Test
148	public void testOnMessage() {
149		Message call = Message.newBuilder()
150		        .setUid(String.valueOf(System.currentTimeMillis()))
151		        .setDate(System.currentTimeMillis())
152		        .setContent(ByteString.copyFrom(new byte[0]))
153		        .setFrom("From")
154		        .setTo("TO")
155		        .build();
156		Message response = Message.newBuilder()
157		        .setUid(String.valueOf(System.currentTimeMillis()))
158		        .setDate(System.currentTimeMillis())
159		        .setContent(ByteString.copyFrom(new byte[0]))
160		        .setFrom("From")
161		        .setTo("TO")
162		        .setReplyFor(call.getUid())
163		        .build();
164
165		@SuppressWarnings("unchecked")
166		Map<String, RPCInvoke> internalMap = (Map<String, RPCInvoke>) ReflectionTestUtils
167		        .getField(service, "rpcRegistry");
168
169		RPCHandler handler = mocksControl.createMock(RPCHandler.class);
170		internalMap.put(call.getUid(), new RPCInvoke(handler, scheduledFuture));
171
172		expect(scheduledFuture.cancel(false))
173		        .andReturn(true)
174		        .once();
175
176		handler.onMessage(same(response));
177		expectLastCall().once();
178
179		mocksControl.replay();
180		service.onMessage(response);
181
182		assertFalse(internalMap.containsKey(call.getUid()));
183	}
184
185	@Test
186	public void testOnMessage如果Handler的onMessage方法抛出异常那么handler的exceptionCause将会被调用() {
187		Message call = Message.newBuilder()
188		        .setUid(String.valueOf(System.currentTimeMillis()))
189		        .setDate(System.currentTimeMillis())
190		        .setContent(ByteString.copyFrom(new byte[0]))
191		        .setFrom("From")
192		        .setTo("TO")
193		        .build();
194		Message response = Message.newBuilder()
195		        .setUid(String.valueOf(System.currentTimeMillis()))
196		        .setDate(System.currentTimeMillis())
197		        .setContent(ByteString.copyFrom(new byte[0]))
198		        .setFrom("From")
199		        .setTo("TO")
200		        .setReplyFor(call.getUid())
201		        .build();
202
203		@SuppressWarnings("unchecked")
204		Map<String, RPCInvoke> internalMap = (Map<String, RPCInvoke>) ReflectionTestUtils
205		        .getField(
206		                service, "rpcRegistry");
207
208		RPCHandler handler = mocksControl.createMock(RPCHandler.class);
209		internalMap.put(call.getUid(), new RPCInvoke(handler, scheduledFuture));
210
211		handler.onMessage(same(response));
212		RuntimeException e = new RuntimeException("Test For onMessage");
213		expectLastCall().andThrow(e)
214		        .once();
215
216		expect(scheduledFuture.cancel(false))
217		        .andReturn(false)
218		        .once();
219
220		handler.exceptionCaught(call, e);
221		expectLastCall().once();
222
223		mocksControl.replay();
224		service.onMessage(response);
225
226		assertFalse(internalMap.containsKey(call.getUid()));
227
228	}
229
230	@Test
231	public void testOnMessage没有对应的调用会导致消息被丢弃() {
232		Message response = Message.newBuilder()
233		        .setUid(String.valueOf(System.currentTimeMillis()))
234		        .setDate(System.currentTimeMillis())
235		        .setContent(ByteString.copyFrom(new byte[0]))
236		        .setFrom("From")
237		        .setTo("TO")
238		        .setReplyFor("xxxxxxx")
239		        .build();
240
241		mocksControl.replay();
242		service.onMessage(response);
243	}
244
245}
246
Full Screen
copy
1/*
2 * Copyright 2008 the original author or authors.
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 samples.junit4.expectnew;
17
18import junit.framework.Assert;
19import org.easymock.EasyMock;
20import org.easymock.internal.MocksControl;
21import org.junit.Test;
22import org.junit.runner.RunWith;
23import org.powermock.api.easymock.PowerMock;
24import org.powermock.core.classloader.annotations.PrepareForTest;
25import org.powermock.modules.junit4.PowerMockRunner;
26import samples.expectnew.ExpectNewDemo;
27
28import java.util.Date;
29
30@RunWith(PowerMockRunner.class)
31@PrepareForTest( { ExpectNewDemo.class })
32public class MockDateTest {
33
34	@Test
35	public void testMockDate() throws Exception {
36		Date someDate = new Date();
37		Date date = PowerMock.createMock(Date.class);
38		EasyMock.expect(date.after(someDate)).andReturn(false);
39
40		PowerMock.replay(date);
41
42		date.after(someDate);
43
44		PowerMock.verify(date);
45	}
46
47	@Test
48	public void testMockDateWithEasyMock() throws Exception {
49		Date someDate = new Date();
50		MocksControl c = (MocksControl) org.easymock.EasyMock.createControl();
51		Date date = c.createMock(Date.class);
52		EasyMock.expect(date.after(someDate)).andReturn(false);
53
54		PowerMock.replay(date);
55
56		date.after(someDate);
57
58		PowerMock.verify(date);
59	}
60
61	@Test(expected = IllegalStateException.class)
62	public void testMockDateWithEasyMockFails() {
63		Date someDate = new Date();
64		MocksControl c = (MocksControl) org.easymock.EasyMock.createControl();
65		Date date = c.createMock(null, Date.class, null);
66		EasyMock.expect(date.after(someDate)).andReturn(false);
67		Assert.fail("EasyMock with no methods mocked should not be possible to mock");
68	}
69
70	@Test
71	public void testExpectNewDate() throws Exception {
72		Date someDate = new Date();
73		long time = someDate.getTime();
74		PowerMock.expectNew(Date.class).andReturn(someDate);
75
76		PowerMock.replay(Date.class);
77
78		Assert.assertEquals(time, new ExpectNewDemo().makeDate().getTime());
79
80		PowerMock.verify(Date.class);
81	}
82}
83
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)