How to use method of org.easymock.tests2.ThreadingTest class

Best Easymock code snippet using org.easymock.tests2.ThreadingTest.

Run Easymock automation tests on LambdaTest cloud grid

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

copy
1/*
2 * Copyright 2001-2021 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 org.easymock.tests2;
17
18import org.easymock.internal.AssertionErrorWrapper;
19import org.easymock.internal.MocksBehavior;
20import org.easymock.tests.IMethods;
21import org.junit.Test;
22
23import java.util.Collections;
24import java.util.List;
25import java.util.concurrent.*;
26
27import static org.easymock.EasyMock.*;
28import static org.junit.Assert.*;
29
30/**
31 * Test that EasyMock works in replay state in a multithreaded environment. Note
32 * that sadly this test isn't sure to fail all the time. Only if there's a
33 * concurrency issue and we're lucky enough to fell on it during testing.
34 *
35 * @author Henri Tremblay
36 */
37public class ThreadingTest {
38
39    private static final int THREAD_COUNT = 10;
40
41    @Test
42    public void testThreadSafe() throws Throwable {
43
44        final IMethods mock = createMock(IMethods.class);
45        expect(mock.oneArg("test")).andReturn("result").times(THREAD_COUNT);
46
47        replay(mock);
48
49        Callable<String> replay = () -> mock.oneArg("test");
50
51        ExecutorService service = Executors.newFixedThreadPool(THREAD_COUNT);
52
53        List<Callable<String>> tasks = Collections.nCopies(THREAD_COUNT, replay);
54
55        List<Future<String>> results = service.invokeAll(tasks);
56
57        for (Future<String> future : results) {
58            assertEquals("result", future.get());
59        }
60
61        verify(mock);
62    }
63
64    @Test
65    public void testThreadNotSafe() throws Throwable {
66
67        final IMethods mock = createMock(IMethods.class);
68        expect(mock.oneArg("test")).andReturn("result").times(THREAD_COUNT);
69
70        makeThreadSafe(mock, false);
71
72        checkIsUsedInOneThread(mock, true);
73
74        replay(mock);
75
76        Callable<String> replay = () -> mock.oneArg("test");
77
78        ExecutorService service = Executors.newFixedThreadPool(THREAD_COUNT);
79
80        List<Callable<String>> tasks = Collections.nCopies(THREAD_COUNT, replay);
81
82        List<Future<String>> results = service.invokeAll(tasks);
83
84        boolean exceptionThrown = false;
85
86        for (Future<String> future : results) {
87            try {
88                assertEquals("result", future.get());
89            } catch (ExecutionException e) {
90                // Since I don't know which one the lastThread is, that's the
91                // best assert I can do except doing
92                // a regular exception and I don't think it worth it
93                assertTrue(e.getCause().getMessage().startsWith(
94                        "\n Mock isn't supposed to be called from multiple threads. Last: "));
95                exceptionThrown = true;
96            }
97        }
98
99        assertTrue(exceptionThrown);
100    }
101
102    @Test
103    public void testMockUsedCorrectly() {
104        IMethods mock = createMock(IMethods.class);
105        expect(mock.oneArg("test")).andReturn("result").times(2);
106
107        checkIsUsedInOneThread(mock, true);
108
109        replay(mock);
110
111        mock.oneArg("test");
112        mock.oneArg("test");
113
114        verify(mock);
115    }
116
117    @Test
118    public void testChangeDefault() throws Throwable {
119        String previousThreadSafetyCheck = setEasyMockProperty(ENABLE_THREAD_SAFETY_CHECK_BY_DEFAULT,
120                Boolean.TRUE.toString());
121        String previousThreadSafe = setEasyMockProperty(NOT_THREAD_SAFE_BY_DEFAULT, Boolean.TRUE
122                .toString());
123        try {
124            final MocksBehavior behavior = new MocksBehavior(true);
125            assertFalse(behavior.isThreadSafe());
126
127            Thread t = new Thread(behavior::checkThreadSafety);
128            t.start();
129            t.join();
130            try {
131                behavior.checkThreadSafety();
132                fail("Shouldn't work");
133            } catch (AssertionErrorWrapper e) {
134
135            }
136
137        } finally {
138            setEasyMockProperty(ENABLE_THREAD_SAFETY_CHECK_BY_DEFAULT, previousThreadSafetyCheck);
139            setEasyMockProperty(NOT_THREAD_SAFE_BY_DEFAULT, previousThreadSafe);
140        }
141    }
142
143    @Test
144    public void testRecordingInMultipleThreads() throws Exception {
145
146        Callable<String> replay = () -> {
147            IMethods mock = createMock(IMethods.class);
148            expect(mock.oneArg("test")).andReturn("result");
149
150            replay(mock);
151
152            String s = mock.oneArg("test");
153
154            verify(mock);
155
156            return s;
157        };
158
159        ExecutorService service = Executors.newFixedThreadPool(THREAD_COUNT);
160
161        List<Callable<String>> tasks = Collections.nCopies(THREAD_COUNT, replay);
162
163        List<Future<String>> results = service.invokeAll(tasks);
164
165        for (Future<String> future : results) {
166            assertEquals("result", future.get());
167        }
168    }
169
170    @SuppressWarnings("unchecked")
171    @Test
172    public void testCleanupAfterFailureInRecordPhase() {
173        Comparable<String> mock = createNiceMock(Comparable.class);
174
175        // Mocking equals() doesn't work
176        try {
177            expect(mock.equals(eq(mock))).andReturn(true);
178        } catch (IllegalStateException e) {
179
180        }
181
182        // However, the recorded matchers should be cleaned to prevent impacting
183        // other tests
184        mock = createNiceMock(Comparable.class);
185        expect(mock.compareTo(isNull())).andReturn(1);
186        replay(mock);
187        assertEquals(1, mock.compareTo(null));
188    }
189}
190
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)