How to use method of org.jmock.test.unit.lib.concurrent.DeterministicSchedulerTests class

Best Jmock-library code snippet using org.jmock.test.unit.lib.concurrent.DeterministicSchedulerTests.

Run Jmock-library automation tests on LambdaTest cloud grid

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

copy
1package org.jmock.test.unit.lib.concurrent;
2
3
4import static org.hamcrest.CoreMatchers.is;
5import static org.hamcrest.Matchers.equalTo;
6import static org.hamcrest.Matchers.sameInstance;
7import static org.junit.Assert.assertThat;
8
9import java.util.concurrent.Callable;
10import java.util.concurrent.ExecutionException;
11import java.util.concurrent.Future;
12import java.util.concurrent.ScheduledExecutorService;
13import java.util.concurrent.ScheduledFuture;
14import java.util.concurrent.TimeUnit;
15import java.util.concurrent.atomic.AtomicInteger;
16
17import org.jmock.Expectations;
18import org.jmock.Sequence;
19import org.jmock.api.Action;
20import org.jmock.lib.concurrent.DeterministicScheduler;
21import org.jmock.lib.concurrent.UnsupportedSynchronousOperationException;
22import org.jmock.test.unit.internal.MockObjectTestCase;
23
24public class DeterministicSchedulerTests extends MockObjectTestCase {
25    DeterministicScheduler scheduler = new DeterministicScheduler();
26    
27    Runnable commandA = mock(Runnable.class, "commandA");
28    Runnable commandB = mock(Runnable.class, "commandB");
29    Runnable commandC = mock(Runnable.class, "commandC");
30    Runnable commandD = mock(Runnable.class, "commandD");
31    
32    @SuppressWarnings("unchecked")
33    Callable<String> callableA = mock(Callable.class, "callableA");
34    
35    public void testRunsPendingCommandsUntilIdle() {
36        scheduler.execute(commandA);
37        scheduler.execute(commandB);
38        
39        final Sequence executionOrder = sequence("executionOrder");
40        
41        checking(new Expectations() {{
42            oneOf (commandA).run(); inSequence(executionOrder);
43            oneOf (commandB).run(); inSequence(executionOrder);
44        }});
45        
46        assertFalse(scheduler.isIdle());
47        
48        scheduler.runUntilIdle();
49        
50        assertTrue(scheduler.isIdle());
51    }
52    
53    public void testCanRunCommandsSpawnedByExecutedCommandsUntilIdle() {
54        scheduler.execute(commandA);
55        scheduler.execute(commandB);
56        
57        final Sequence executionOrder = sequence("executionOrder");
58        
59        checking(new Expectations() {{
60            oneOf (commandA).run(); inSequence(executionOrder); will(schedule(commandC));
61            oneOf (commandB).run(); inSequence(executionOrder); will(schedule(commandD));
62            oneOf (commandC).run(); inSequence(executionOrder);
63            oneOf (commandD).run(); inSequence(executionOrder);
64        }});
65        
66        scheduler.runUntilIdle();
67    }
68    
69    public void testCanScheduleCommandAndReturnFuture() throws InterruptedException, ExecutionException {
70        Future<?> future = scheduler.submit(commandA);
71        
72        checking(new Expectations() {{
73            oneOf (commandA).run();
74        }});
75        
76        assertTrue("future should not be done before running the task", !future.isDone());
77        
78        scheduler.runUntilIdle();
79        
80        assertTrue("future should be done after running the task", future.isDone());
81        assertNull("result of future should be null", future.get());
82    }
83    
84    public void testCanScheduleCommandAndResultAndReturnFuture() throws InterruptedException, ExecutionException {
85        Future<String> future = scheduler.submit(commandA, "result1");
86        
87        checking(new Expectations() {{
88            oneOf (commandA).run();
89        }});
90       
91        scheduler.runUntilIdle();
92        
93        assertThat(future.get(), equalTo("result1"));
94    }
95
96    public void testCanScheduleCallableAndReturnFuture() throws Exception {
97        Future<String> future = scheduler.submit(callableA);
98        
99        checking(new Expectations() {{
100            oneOf (callableA).call(); will(returnValue("result2"));
101        }});
102        
103        scheduler.runUntilIdle();
104        
105        assertThat(future.get(), equalTo("result2"));
106    }
107
108    public void testScheduledCallablesCanReturnNull() throws Exception {
109        checking(new Expectations() {{
110            oneOf (callableA).call(); will(returnValue(null));
111        }});
112        
113        Future<String> future = scheduler.submit(callableA);
114        
115        scheduler.runUntilIdle();
116        
117        assertNull(future.get());
118    }
119
120    public void testSimpleGetDelay() throws Exception {
121        ScheduledFuture<?> task1 = scheduler.schedule(commandA, 10, TimeUnit.SECONDS);
122        scheduler.tick(1, TimeUnit.SECONDS);
123        assertEquals(9, task1.getDelay(TimeUnit.SECONDS));
124    }
125
126    public void testGetDelayWithManyScheduledTasks() throws Exception {
127        ScheduledFuture<?> task1 = scheduler.schedule(commandA, 10, TimeUnit.SECONDS);
128        ScheduledFuture<?> task2 = scheduler.schedule(commandA, 20, TimeUnit.SECONDS);
129        ScheduledFuture<?> task3 = scheduler.schedule(commandA, 15, TimeUnit.SECONDS);
130
131        scheduler.tick(5, TimeUnit.SECONDS);
132
133        assertEquals(5, task1.getDelay(TimeUnit.SECONDS));
134        assertEquals(15, task2.getDelay(TimeUnit.SECONDS));
135        assertEquals(10, task3.getDelay(TimeUnit.SECONDS));
136    }
137
138    public void testGetDelayOnPassedTasks() throws Exception {
139        final Throwable thrown = new IllegalStateException();
140
141        ScheduledFuture<?> task1 = scheduler.schedule(commandA, 1, TimeUnit.MILLISECONDS);
142
143        checking(new Expectations() {{
144            oneOf (commandA).run(); will(throwException(thrown));
145        }});
146
147        scheduler.tick(2, TimeUnit.MILLISECONDS);
148
149        assertEquals(-1, task1.getDelay(TimeUnit.MILLISECONDS));
150    }
151    
152    public class ExampleException extends Exception {}
153    
154    public void testExceptionThrownByScheduledCallablesIsThrownFromFuture() throws Exception {
155        final Throwable thrown = new ExampleException();
156        
157        checking(new Expectations() {{
158            oneOf (callableA).call(); will(throwException(thrown));
159        }});
160        
161        Future<String> future = scheduler.submit(callableA);
162        
163        scheduler.runUntilIdle();
164        
165        try {
166            future.get();
167            fail("should have thrown ExecutionException");
168        }
169        catch (ExecutionException expected) {
170            assertThat(expected.getCause(), sameInstance(thrown));
171        }
172    }
173
174    public void testCanScheduleCommandsToBeExecutedAfterADelay() {
175        scheduler.schedule(commandA, 10, TimeUnit.SECONDS);
176        
177        scheduler.tick(9, TimeUnit.SECONDS);
178        
179        checking(new Expectations() {{
180            oneOf (commandA).run();
181        }});
182        
183        scheduler.tick(1, TimeUnit.SECONDS);
184    }
185    
186    public void testTickingTimeForwardRunsAllCommandsScheduledDuringThatTimePeriod() {
187        scheduler.schedule(commandA, 1, TimeUnit.MILLISECONDS);
188        scheduler.schedule(commandB, 2, TimeUnit.MILLISECONDS);
189        
190        checking(new Expectations() {{
191            oneOf (commandA).run();
192            oneOf (commandB).run();
193        }});
194        
195        scheduler.tick(3, TimeUnit.MILLISECONDS);
196    }
197    
198    public void testTickingTimeForwardRunsCommandsExecutedByScheduledCommands() {
199        scheduler.schedule(commandA, 1, TimeUnit.MILLISECONDS);
200        scheduler.schedule(commandD, 2, TimeUnit.MILLISECONDS);
201        
202        checking(new Expectations() {{
203            oneOf (commandA).run(); will(schedule(commandB));
204            oneOf (commandB).run(); will(schedule(commandC));
205            oneOf (commandC).run();
206            oneOf (commandD).run();
207        }});
208        
209        scheduler.tick(3, TimeUnit.MILLISECONDS);
210    }
211    
212    public void testCanExecuteCommandsThatRepeatWithFixedDelay() {
213        scheduler.scheduleWithFixedDelay(commandA, 2L, 3L, TimeUnit.SECONDS);
214        
215        checking(new Expectations() {{
216            exactly(3).of(commandA).run();
217        }});
218        
219        scheduler.tick(8L, TimeUnit.SECONDS);
220    }
221
222    public void testCanExecuteCommandsThatRepeatAtFixedRateButAssumesThatCommandsTakeNoTimeToExecute() {
223        scheduler.scheduleAtFixedRate(commandA, 2L, 3L, TimeUnit.SECONDS);
224        
225        checking(new Expectations() {{
226            exactly(3).of(commandA).run();
227        }});
228        
229        scheduler.tick(8L, TimeUnit.SECONDS);
230    }
231    
232    public void testCanCancelScheduledCommands() {
233        final boolean dontCare = true;
234        ScheduledFuture<?> future = scheduler.schedule(commandA, 1, TimeUnit.SECONDS);
235        
236        assertFalse(future.isCancelled());
237        future.cancel(dontCare);
238        assertTrue(future.isCancelled());
239        
240        checking(new Expectations() {{
241            never (commandA);
242        }});
243        
244        scheduler.tick(2, TimeUnit.SECONDS);
245    }
246
247    public void testCancellingARunningCommandStopsItFromRunningAgain() {
248        DeterministicScheduler deterministicScheduler = new DeterministicScheduler();
249        ObjectThatCancelsARepeatingTask objectThatCancelsARepeatingTask = new ObjectThatCancelsARepeatingTask(deterministicScheduler);
250        objectThatCancelsARepeatingTask.scheduleATaskThatWillCancelItself(1, TimeUnit.SECONDS);
251        deterministicScheduler.tick(2,TimeUnit.SECONDS);
252        assertThat("cancelling runnable run count", objectThatCancelsARepeatingTask.runCount(), is(1));
253    }
254    public static class ObjectThatCancelsARepeatingTask {
255
256        private final ScheduledExecutorService scheduler;
257        private ScheduledFuture<?> scheduledFuture;
258        private final AtomicInteger counter = new AtomicInteger();
259        public ObjectThatCancelsARepeatingTask(ScheduledExecutorService scheduler) {
260            this.scheduler = scheduler;
261        }
262        public void scheduleATaskThatWillCancelItself(int interval, TimeUnit unit){
263            scheduledFuture = scheduler.scheduleAtFixedRate(
264                    new CancellingRunnable(), interval,interval,unit);
265        }
266        public int runCount(){
267            return counter.get();
268        }
269        private class CancellingRunnable implements Runnable{
270            @Override
271            public void run() {
272                scheduledFuture.cancel(true);
273                counter.incrementAndGet();
274            }
275        }
276    }
277    static final int TIMEOUT_IGNORED = 1000;
278    
279    public void testCanScheduleCallablesAndGetTheirResultAfterTheyHaveBeenExecuted() throws Exception {
280        checking(new Expectations() {{
281            oneOf (callableA).call(); will(returnValue("A"));
282        }});
283        
284        ScheduledFuture<String> future = scheduler.schedule(callableA, 1, TimeUnit.SECONDS);
285        
286        assertTrue("is not done", !future.isDone());
287        
288        scheduler.tick(1, TimeUnit.SECONDS);
289        
290        assertTrue("is done", future.isDone());
291        assertThat(future.get(), equalTo("A"));
292        assertThat(future.get(TIMEOUT_IGNORED, TimeUnit.SECONDS), equalTo("A"));
293    }
294
295    public void testCannotBlockWaitingForFutureResultOfScheduledCallable() throws Exception {
296        ScheduledFuture<String> future = scheduler.schedule(callableA, 1, TimeUnit.SECONDS);
297        
298        try {
299            future.get();
300            fail("should have thrown UnsupportedSynchronousOperationException");
301        }
302        catch (UnsupportedSynchronousOperationException expected) {}
303        
304        try {
305            future.get(TIMEOUT_IGNORED, TimeUnit.SECONDS);
306            fail("should have thrown UnsupportedSynchronousOperationException");
307        }
308        catch (UnsupportedSynchronousOperationException expected) {}
309    }
310    
311    private Action schedule(final Runnable command) {
312        return ScheduleOnExecutorAction.schedule(scheduler, command);
313    }
314}
315
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)