How to use method of org.mockito.Mockito class

Best Mockito code snippet using org.mockito.Mockito.

Run Mockito automation tests on LambdaTest cloud grid

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

copy
1/**
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *     http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19package org.apache.hadoop.ha;
20
21import static org.junit.Assert.assertFalse;
22import static org.junit.Assert.assertTrue;
23
24import java.util.Collections;
25import java.util.UUID;
26
27import org.apache.commons.logging.impl.Log4JLogger;
28import org.apache.hadoop.fs.CommonConfigurationKeys;
29import org.apache.hadoop.ha.ActiveStandbyElector.ActiveStandbyElectorCallback;
30import org.apache.hadoop.ha.ActiveStandbyElector.State;
31import org.apache.hadoop.util.ZKUtil.ZKAuthInfo;
32import org.apache.log4j.Level;
33import org.apache.zookeeper.ZooDefs.Ids;
34import org.apache.zookeeper.server.ZooKeeperServer;
35import org.junit.Test;
36import org.mockito.AdditionalMatchers;
37import org.mockito.Mockito;
38
39import com.google.common.primitives.Ints;
40
41/**
42 * Test for {@link ActiveStandbyElector} using real zookeeper.
43 */
44public class TestActiveStandbyElectorRealZK extends ClientBaseWithFixes {
45  static final int NUM_ELECTORS = 2;
46  
47  static {
48    ((Log4JLogger)ActiveStandbyElector.LOG).getLogger().setLevel(
49        Level.ALL);
50  }
51  
52  static final String PARENT_DIR = "/" + UUID.randomUUID();
53
54  ActiveStandbyElector[] electors = new ActiveStandbyElector[NUM_ELECTORS];
55  private byte[][] appDatas = new byte[NUM_ELECTORS][];
56  private ActiveStandbyElectorCallback[] cbs =
57      new ActiveStandbyElectorCallback[NUM_ELECTORS];
58  private ZooKeeperServer zkServer;
59
60  
61  @Override
62  public void setUp() throws Exception {
63    super.setUp();
64    
65    zkServer = getServer(serverFactory);
66
67    for (int i = 0; i < NUM_ELECTORS; i++) {
68      cbs[i] =  Mockito.mock(ActiveStandbyElectorCallback.class);
69      appDatas[i] = Ints.toByteArray(i);
70      electors[i] = new ActiveStandbyElector(hostPort, 5000, PARENT_DIR,
71          Ids.OPEN_ACL_UNSAFE, Collections.<ZKAuthInfo> emptyList(), cbs[i],
72          CommonConfigurationKeys.HA_FC_ELECTOR_ZK_OP_RETRIES_DEFAULT);
73    }
74  }
75  
76  private void checkFatalsAndReset() throws Exception {
77    for (int i = 0; i < NUM_ELECTORS; i++) {
78      Mockito.verify(cbs[i], Mockito.never()).notifyFatalError(
79          Mockito.anyString());
80      Mockito.reset(cbs[i]);
81    }
82  }
83
84  /**
85   * the test creates 2 electors which try to become active using a real
86   * zookeeper server. It verifies that 1 becomes active and 1 becomes standby.
87   * Upon becoming active the leader quits election and the test verifies that
88   * the standby now becomes active.
89   */
90  @Test(timeout=20000)
91  public void testActiveStandbyTransition() throws Exception {
92    LOG.info("starting test with parentDir:" + PARENT_DIR);
93
94    assertFalse(electors[0].parentZNodeExists());
95    electors[0].ensureParentZNode();
96    assertTrue(electors[0].parentZNodeExists());
97
98    // First elector joins election, becomes active.
99    electors[0].joinElection(appDatas[0]);
100    ActiveStandbyElectorTestUtil.waitForActiveLockData(null,
101        zkServer, PARENT_DIR, appDatas[0]);
102    Mockito.verify(cbs[0], Mockito.timeout(1000)).becomeActive();
103    checkFatalsAndReset();
104
105    // Second elector joins election, becomes standby.
106    electors[1].joinElection(appDatas[1]);
107    Mockito.verify(cbs[1], Mockito.timeout(1000)).becomeStandby();
108    checkFatalsAndReset();
109    
110    // First elector quits, second one should become active
111    electors[0].quitElection(true);
112    ActiveStandbyElectorTestUtil.waitForActiveLockData(null,
113        zkServer, PARENT_DIR, appDatas[1]);
114    Mockito.verify(cbs[1], Mockito.timeout(1000)).becomeActive();
115    checkFatalsAndReset();
116    
117    // First one rejoins, becomes standby, second one stays active
118    electors[0].joinElection(appDatas[0]);
119    Mockito.verify(cbs[0], Mockito.timeout(1000)).becomeStandby();
120    checkFatalsAndReset();
121    
122    // Second one expires, first one becomes active
123    electors[1].preventSessionReestablishmentForTests();
124    try {
125      zkServer.closeSession(electors[1].getZKSessionIdForTests());
126      
127      ActiveStandbyElectorTestUtil.waitForActiveLockData(null,
128          zkServer, PARENT_DIR, appDatas[0]);
129      Mockito.verify(cbs[1], Mockito.timeout(1000)).enterNeutralMode();
130      Mockito.verify(cbs[0], Mockito.timeout(1000)).fenceOldActive(
131          AdditionalMatchers.aryEq(appDatas[1]));
132      Mockito.verify(cbs[0], Mockito.timeout(1000)).becomeActive();
133    } finally {
134      electors[1].allowSessionReestablishmentForTests();
135    }
136    
137    // Second one eventually reconnects and becomes standby
138    Mockito.verify(cbs[1], Mockito.timeout(5000)).becomeStandby();
139    checkFatalsAndReset();
140    
141    // First one expires, second one should become active
142    electors[0].preventSessionReestablishmentForTests();
143    try {
144      zkServer.closeSession(electors[0].getZKSessionIdForTests());
145      
146      ActiveStandbyElectorTestUtil.waitForActiveLockData(null,
147          zkServer, PARENT_DIR, appDatas[1]);
148      Mockito.verify(cbs[0], Mockito.timeout(1000)).enterNeutralMode();
149      Mockito.verify(cbs[1], Mockito.timeout(1000)).fenceOldActive(
150          AdditionalMatchers.aryEq(appDatas[0]));
151      Mockito.verify(cbs[1], Mockito.timeout(1000)).becomeActive();
152    } finally {
153      electors[0].allowSessionReestablishmentForTests();
154    }
155    
156    checkFatalsAndReset();
157  }
158  
159  @Test(timeout=15000)
160  public void testHandleSessionExpiration() throws Exception {
161    ActiveStandbyElectorCallback cb = cbs[0];
162    byte[] appData = appDatas[0];
163    ActiveStandbyElector elector = electors[0];
164    
165    // Let the first elector become active
166    elector.ensureParentZNode();
167    elector.joinElection(appData);
168    ZooKeeperServer zks = getServer(serverFactory);
169    ActiveStandbyElectorTestUtil.waitForActiveLockData(null,
170        zks, PARENT_DIR, appData);
171    Mockito.verify(cb, Mockito.timeout(1000)).becomeActive();
172    checkFatalsAndReset();
173    
174    LOG.info("========================== Expiring session");
175    zks.closeSession(elector.getZKSessionIdForTests());
176
177    // Should enter neutral mode when disconnected
178    Mockito.verify(cb, Mockito.timeout(1000)).enterNeutralMode();
179
180    // Should re-join the election and regain active
181    ActiveStandbyElectorTestUtil.waitForActiveLockData(null,
182        zks, PARENT_DIR, appData);
183    Mockito.verify(cb, Mockito.timeout(1000)).becomeActive();
184    checkFatalsAndReset();
185    
186    LOG.info("========================== Quitting election");
187    elector.quitElection(false);
188    ActiveStandbyElectorTestUtil.waitForActiveLockData(null,
189        zks, PARENT_DIR, null);
190
191    // Double check that we don't accidentally re-join the election
192    // due to receiving the "expired" event.
193    Thread.sleep(1000);
194    Mockito.verify(cb, Mockito.never()).becomeActive();
195    ActiveStandbyElectorTestUtil.waitForActiveLockData(null,
196        zks, PARENT_DIR, null);
197
198    checkFatalsAndReset();
199  }
200  
201  @Test(timeout=15000)
202  public void testHandleSessionExpirationOfStandby() throws Exception {
203    // Let elector 0 be active
204    electors[0].ensureParentZNode();
205    electors[0].joinElection(appDatas[0]);
206    ZooKeeperServer zks = getServer(serverFactory);
207    ActiveStandbyElectorTestUtil.waitForActiveLockData(null,
208        zks, PARENT_DIR, appDatas[0]);
209    Mockito.verify(cbs[0], Mockito.timeout(1000)).becomeActive();
210    checkFatalsAndReset();
211    
212    // Let elector 1 be standby
213    electors[1].joinElection(appDatas[1]);
214    ActiveStandbyElectorTestUtil.waitForElectorState(null, electors[1],
215        State.STANDBY);
216    
217    LOG.info("========================== Expiring standby's session");
218    zks.closeSession(electors[1].getZKSessionIdForTests());
219
220    // Should enter neutral mode when disconnected
221    Mockito.verify(cbs[1], Mockito.timeout(1000)).enterNeutralMode();
222
223    // Should re-join the election and go back to STANDBY
224    ActiveStandbyElectorTestUtil.waitForElectorState(null, electors[1],
225        State.STANDBY);
226    checkFatalsAndReset();
227    
228    LOG.info("========================== Quitting election");
229    electors[1].quitElection(false);
230
231    // Double check that we don't accidentally re-join the election
232    // by quitting elector 0 and ensuring elector 1 doesn't become active
233    electors[0].quitElection(false);
234    
235    // due to receiving the "expired" event.
236    Thread.sleep(1000);
237    Mockito.verify(cbs[1], Mockito.never()).becomeActive();
238    ActiveStandbyElectorTestUtil.waitForActiveLockData(null,
239        zks, PARENT_DIR, null);
240
241    checkFatalsAndReset();
242  }
243
244  @Test(timeout=15000)
245  public void testDontJoinElectionOnDisconnectAndReconnect() throws Exception {
246    electors[0].ensureParentZNode();
247
248    stopServer();
249    ActiveStandbyElectorTestUtil.waitForElectorState(
250        null, electors[0], State.NEUTRAL);
251    startServer();
252    waitForServerUp(hostPort, CONNECTION_TIMEOUT);
253    // Have to sleep to allow time for the clients to reconnect.
254    Thread.sleep(2000);
255    Mockito.verify(cbs[0], Mockito.never()).becomeActive();
256    Mockito.verify(cbs[1], Mockito.never()).becomeActive();
257    checkFatalsAndReset();
258  }
259}
260
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)