Best Mockito code snippet using org.mockito.Mockito.timeout
Source:TestInternalExecRuntime.java
...108 public void testAcquireEndpointLeaseRequestTimeout() throws Exception {109 final HttpClientContext context = HttpClientContext.create();110 Mockito.when(mgr.lease(Mockito.eq("some-id"), Mockito.eq(route), Mockito.<Timeout>any(), Mockito.any()))111 .thenReturn(leaseRequest);112 Mockito.when(leaseRequest.get(Mockito.<Timeout>any())).thenThrow(new TimeoutException("timeout"));113 execRuntime.acquireEndpoint("some-id", route, null, context);114 }115 @Test(expected = RequestFailedException.class)116 public void testAcquireEndpointLeaseRequestFailure() throws Exception {117 final HttpClientContext context = HttpClientContext.create();118 Mockito.when(mgr.lease(Mockito.eq("some-id"), Mockito.eq(route), Mockito.<Timeout>any(), Mockito.any()))119 .thenReturn(leaseRequest);120 Mockito.when(leaseRequest.get(Mockito.<Timeout>any())).thenThrow(new ExecutionException(new IllegalStateException()));121 execRuntime.acquireEndpoint("some-id", route, null, context);122 }123 @Test124 public void testAbortEndpoint() throws Exception {125 final HttpClientContext context = HttpClientContext.create();126 Mockito.when(mgr.lease(Mockito.eq("some-id"), Mockito.eq(route), Mockito.<Timeout>any(), Mockito.any()))...
Source:TestActiveStandbyElectorRealZK.java
...76 * zookeeper server. It verifies that 1 becomes active and 1 becomes standby.77 * Upon becoming active the leader quits election and the test verifies that78 * the standby now becomes active.79 */80 @Test(timeout=20000)81 public void testActiveStandbyTransition() throws Exception {82 LOG.info("starting test with parentDir:" + PARENT_DIR);83 assertFalse(electors[0].parentZNodeExists());84 electors[0].ensureParentZNode();85 assertTrue(electors[0].parentZNodeExists());86 // First elector joins election, becomes active.87 electors[0].joinElection(appDatas[0]);88 ActiveStandbyElectorTestUtil.waitForActiveLockData(null,89 zkServer, PARENT_DIR, appDatas[0]);90 Mockito.verify(cbs[0], Mockito.timeout(1000)).becomeActive();91 checkFatalsAndReset();92 // Second elector joins election, becomes standby.93 electors[1].joinElection(appDatas[1]);94 Mockito.verify(cbs[1], Mockito.timeout(1000)).becomeStandby();95 checkFatalsAndReset();96 97 // First elector quits, second one should become active98 electors[0].quitElection(true);99 ActiveStandbyElectorTestUtil.waitForActiveLockData(null,100 zkServer, PARENT_DIR, appDatas[1]);101 Mockito.verify(cbs[1], Mockito.timeout(1000)).becomeActive();102 checkFatalsAndReset();103 104 // First one rejoins, becomes standby, second one stays active105 electors[0].joinElection(appDatas[0]);106 Mockito.verify(cbs[0], Mockito.timeout(1000)).becomeStandby();107 checkFatalsAndReset();108 109 // Second one expires, first one becomes active110 electors[1].preventSessionReestablishmentForTests();111 try {112 zkServer.closeSession(electors[1].getZKSessionIdForTests());113 114 ActiveStandbyElectorTestUtil.waitForActiveLockData(null,115 zkServer, PARENT_DIR, appDatas[0]);116 Mockito.verify(cbs[1], Mockito.timeout(1000)).enterNeutralMode();117 Mockito.verify(cbs[0], Mockito.timeout(1000)).fenceOldActive(118 AdditionalMatchers.aryEq(appDatas[1]));119 Mockito.verify(cbs[0], Mockito.timeout(1000)).becomeActive();120 } finally {121 electors[1].allowSessionReestablishmentForTests();122 }123 124 // Second one eventually reconnects and becomes standby125 Mockito.verify(cbs[1], Mockito.timeout(5000)).becomeStandby();126 checkFatalsAndReset();127 128 // First one expires, second one should become active129 electors[0].preventSessionReestablishmentForTests();130 try {131 zkServer.closeSession(electors[0].getZKSessionIdForTests());132 133 ActiveStandbyElectorTestUtil.waitForActiveLockData(null,134 zkServer, PARENT_DIR, appDatas[1]);135 Mockito.verify(cbs[0], Mockito.timeout(1000)).enterNeutralMode();136 Mockito.verify(cbs[1], Mockito.timeout(1000)).fenceOldActive(137 AdditionalMatchers.aryEq(appDatas[0]));138 Mockito.verify(cbs[1], Mockito.timeout(1000)).becomeActive();139 } finally {140 electors[0].allowSessionReestablishmentForTests();141 }142 143 checkFatalsAndReset();144 }145 146 @Test(timeout=15000)147 public void testHandleSessionExpiration() throws Exception {148 ActiveStandbyElectorCallback cb = cbs[0];149 byte[] appData = appDatas[0];150 ActiveStandbyElector elector = electors[0];151 152 // Let the first elector become active153 elector.ensureParentZNode();154 elector.joinElection(appData);155 ZooKeeperServer zks = getServer(serverFactory);156 ActiveStandbyElectorTestUtil.waitForActiveLockData(null,157 zks, PARENT_DIR, appData);158 Mockito.verify(cb, Mockito.timeout(1000)).becomeActive();159 checkFatalsAndReset();160 161 LOG.info("========================== Expiring session");162 zks.closeSession(elector.getZKSessionIdForTests());163 // Should enter neutral mode when disconnected164 Mockito.verify(cb, Mockito.timeout(1000)).enterNeutralMode();165 // Should re-join the election and regain active166 ActiveStandbyElectorTestUtil.waitForActiveLockData(null,167 zks, PARENT_DIR, appData);168 Mockito.verify(cb, Mockito.timeout(1000)).becomeActive();169 checkFatalsAndReset();170 171 LOG.info("========================== Quitting election");172 elector.quitElection(false);173 ActiveStandbyElectorTestUtil.waitForActiveLockData(null,174 zks, PARENT_DIR, null);175 // Double check that we don't accidentally re-join the election176 // due to receiving the "expired" event.177 Thread.sleep(1000);178 Mockito.verify(cb, Mockito.never()).becomeActive();179 ActiveStandbyElectorTestUtil.waitForActiveLockData(null,180 zks, PARENT_DIR, null);181 checkFatalsAndReset();182 }183 184 @Test(timeout=15000)185 public void testHandleSessionExpirationOfStandby() throws Exception {186 // Let elector 0 be active187 electors[0].ensureParentZNode();188 electors[0].joinElection(appDatas[0]);189 ZooKeeperServer zks = getServer(serverFactory);190 ActiveStandbyElectorTestUtil.waitForActiveLockData(null,191 zks, PARENT_DIR, appDatas[0]);192 Mockito.verify(cbs[0], Mockito.timeout(1000)).becomeActive();193 checkFatalsAndReset();194 195 // Let elector 1 be standby196 electors[1].joinElection(appDatas[1]);197 ActiveStandbyElectorTestUtil.waitForElectorState(null, electors[1],198 State.STANDBY);199 200 LOG.info("========================== Expiring standby's session");201 zks.closeSession(electors[1].getZKSessionIdForTests());202 // Should enter neutral mode when disconnected203 Mockito.verify(cbs[1], Mockito.timeout(1000)).enterNeutralMode();204 // Should re-join the election and go back to STANDBY205 ActiveStandbyElectorTestUtil.waitForElectorState(null, electors[1],206 State.STANDBY);207 checkFatalsAndReset();208 209 LOG.info("========================== Quitting election");210 electors[1].quitElection(false);211 // Double check that we don't accidentally re-join the election212 // by quitting elector 0 and ensuring elector 1 doesn't become active213 electors[0].quitElection(false);214 215 // due to receiving the "expired" event.216 Thread.sleep(1000);217 Mockito.verify(cbs[1], Mockito.never()).becomeActive();218 ActiveStandbyElectorTestUtil.waitForActiveLockData(null,219 zks, PARENT_DIR, null);220 checkFatalsAndReset();221 }222 @Test(timeout=15000)223 public void testDontJoinElectionOnDisconnectAndReconnect() throws Exception {224 electors[0].ensureParentZNode();225 stopServer();226 ActiveStandbyElectorTestUtil.waitForElectorState(227 null, electors[0], State.NEUTRAL);228 startServer();229 waitForServerUp(hostPort, CONNECTION_TIMEOUT);230 // Have to sleep to allow time for the clients to reconnect.231 Thread.sleep(2000);232 Mockito.verify(cbs[0], Mockito.never()).becomeActive();233 Mockito.verify(cbs[1], Mockito.never()).becomeActive();234 checkFatalsAndReset();235 }236}...
Source:NacosConfigServiceTest.java
...60 public void testGetConfig() throws NacosException {61 final String dataId = "1";62 final String group = "2";63 final String tenant = "";64 final int timeout = 3000;65 ConfigResponse response = new ConfigResponse();66 response.setContent("aa");67 response.setConfigType("bb");68 Mockito.when(mockWoker.getServerConfig(dataId, group, "", timeout, false)).thenReturn(response);69 final String config = nacosConfigService.getConfig(dataId, group, timeout);70 Assert.assertEquals("aa", config);71 Mockito.verify(mockWoker, Mockito.times(1)).getServerConfig(dataId, group, tenant, timeout, false);72 73 }74 75 @Test76 public void testGetConfigAndSignListener() throws NacosException {77 final String dataId = "1";78 final String group = "2";79 final String tenant = "";80 final String content = "123";81 final int timeout = 3000;82 final Listener listener = new Listener() {83 @Override84 public Executor getExecutor() {85 return null;86 }87 88 @Override89 public void receiveConfigInfo(String configInfo) {90 91 }92 };93 94 ConfigResponse response = new ConfigResponse();95 response.setContent(content);96 response.setConfigType("bb");97 Mockito.when(mockWoker.getServerConfig(dataId, group, "", timeout, false)).thenReturn(response);98 99 final String config = nacosConfigService.getConfigAndSignListener(dataId, group, timeout, listener);100 Assert.assertEquals(content, config);101 102 Mockito.verify(mockWoker, Mockito.times(1)).getServerConfig(dataId, group, tenant, timeout, false);103 Mockito.verify(mockWoker, Mockito.times(1))104 .addTenantListenersWithContent(dataId, group, content, Arrays.asList(listener));105 106 }107 108 @Test109 public void testAddListener() throws NacosException {110 String dataId = "1";111 String group = "2";112 Listener listener = new Listener() {113 @Override114 public Executor getExecutor() {115 return null;116 }...
Source:WXTimerModuleTest.java
1/*2 * Licensed to the Apache Software Foundation (ASF) under one3 * or more contributor license agreements. See the NOTICE file4 * distributed with this work for additional information5 * regarding copyright ownership. The ASF licenses this file6 * to you under the Apache License, Version 2.0 (the7 * "License"); you may not use this file except in compliance8 * with the License. You may obtain a copy of the License at9 * 10 * http://www.apache.org/licenses/LICENSE-2.011 * 12 * Unless required by applicable law or agreed to in writing,13 * software distributed under the License is distributed on an14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY15 * KIND, either express or implied. See the License for the16 * specific language governing permissions and limitations17 * under the License.18 */19package org.apache.weex.ui.module;20import static org.hamcrest.CoreMatchers.is;21import static org.junit.Assert.assertThat;22import static org.mockito.Matchers.any;23import static org.mockito.Mockito.never;24import static org.mockito.Mockito.times;25import static org.mockito.Mockito.when;26import android.os.Handler;27import android.os.Message;28import com.taobao.weappplus_sdk.BuildConfig;29import org.apache.weex.InitConfig;30import org.apache.weex.WXSDKEngine;31import org.apache.weex.WXSDKInstanceTest;32import org.apache.weex.bridge.WXBridgeManager;33import org.apache.weex.bridge.WXBridgeManagerTest;34import org.apache.weex.common.WXThread;35import java.util.concurrent.TimeUnit;36import org.junit.Before;37import org.junit.Rule;38import org.junit.Test;39import org.junit.runner.RunWith;40import org.mockito.Mockito;41import org.powermock.core.classloader.annotations.PowerMockIgnore;42import org.powermock.core.classloader.annotations.PrepareForTest;43import org.powermock.modules.junit4.rule.PowerMockRule;44import org.robolectric.RobolectricTestRunner;45import org.robolectric.RuntimeEnvironment;46import org.robolectric.Shadows;47import org.robolectric.annotation.Config;48import org.robolectric.shadows.ShadowLooper;49@RunWith(RobolectricTestRunner.class)50@Config(constants = BuildConfig.class)51@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"})52@PrepareForTest(WXBridgeManager.class)53public class WXTimerModuleTest {54 public final static int VALID_FUNC_ID = 20;55 public final static int NO_CACHING_FUNC_ID = 565654;56 public final static int INVALID_FUNC_ID = 0;57 public final static int DELAY = 50;58 public final static int IMMEDIATELY = 0;59 public final static int INVALID_DELAY = -50;60 @Rule61 public PowerMockRule rule = new PowerMockRule();62 WXTimerModule module;63 ShadowLooper mLooper;64 @Before65 public void setup() throws Exception {66 WXSDKEngine.initialize(RuntimeEnvironment.application, new InitConfig.Builder().build());67 WXBridgeManager bridge = Mockito.mock(WXBridgeManager.class);68 when(bridge.getJSLooper()).thenReturn(new WXThread("js").getLooper());69 WXBridgeManagerTest.setBridgeManager(bridge);70 module = Mockito.spy(new WXTimerModule());71 module.mWXSDKInstance = WXSDKInstanceTest.createInstance();72 Handler handler = new Handler(WXBridgeManager.getInstance().getJSLooper(), module);73 mLooper = Shadows.shadowOf(handler.getLooper());74 module.setHandler(handler);75 }76 @Test77 public void testSetTimeoutDelay() throws Exception {78 module.setTimeout(VALID_FUNC_ID, DELAY);79 mLooper.idle(DELAY);80 Mockito.verify(module, times(1)).handleMessage(any(Message.class));81 }82 @Test83 public void testSetTimeoutImmediately() throws Exception {84 module.setTimeout(VALID_FUNC_ID, IMMEDIATELY);85 mLooper.idle(IMMEDIATELY);86 Mockito.verify(module, times(1)).handleMessage(any(Message.class));87 }88 @SuppressWarnings("Range")89 @Test90 public void testSetTimeoutError1() throws Exception {91 module.setTimeout(INVALID_FUNC_ID, DELAY);92 mLooper.idle(DELAY);93 Mockito.verify(module, never()).handleMessage(any(Message.class));94 }95 @SuppressWarnings("Range")96 @Test97 public void testSetTimeoutError2() throws Exception {98 module.setTimeout(VALID_FUNC_ID, INVALID_DELAY);99 mLooper.runToEndOfTasks();100 Mockito.verify(module, never()).handleMessage(any(Message.class));101 }102 @SuppressWarnings("Range")103 @Test104 public void testSetIntervalError1() throws Exception {105 module.setInterval(INVALID_FUNC_ID, DELAY);106 mLooper.idle(DELAY);107 Mockito.verify(module, never()).handleMessage(any(Message.class));108 }109 @SuppressWarnings("Range")110 @Test111 public void testSetIntervalError2() throws Exception {112 module.setInterval(VALID_FUNC_ID, INVALID_DELAY);113 mLooper.runToEndOfTasks();114 Mockito.verify(module, never()).handleMessage(any(Message.class));115 }116 @Test117 public void testSetIntervalImmediately() throws Exception {118 long start, end, duration;119 module.setInterval(VALID_FUNC_ID, DELAY);120 start = mLooper.getScheduler().getCurrentTime();121 mLooper.runOneTask();122 end = mLooper.getScheduler().getCurrentTime();123 duration = end - start;124 assertThat(duration, is((long) DELAY));125 mLooper.runOneTask();126 mLooper.runOneTask();127 mLooper.runOneTask();128 mLooper.runOneTask();129 Mockito.verify(module, times(5)).handleMessage(any(Message.class));130 }131 @Test132 public void testSetIntervalDelay() {133 long start, end, duration;134 module.setInterval(VALID_FUNC_ID, DELAY);135 start = mLooper.getScheduler().getCurrentTime();136 mLooper.runOneTask();137 end = mLooper.getScheduler().getCurrentTime();138 duration = end - start;139 assertThat(duration, is((long) DELAY));140 mLooper.runOneTask();141 mLooper.runOneTask();142 Mockito.verify(module, times(3)).handleMessage(any(Message.class));143 }144 @Test145 public void testClearTimeout() throws Exception {146 module.setTimeout(VALID_FUNC_ID, DELAY);147 module.clearTimeout(VALID_FUNC_ID);148 mLooper.idle(DELAY, TimeUnit.MILLISECONDS);149 Mockito.verify(module, never()).handleMessage(any(Message.class));150 }151 @Test152 public void testClearInterval() throws Exception {153 module.setInterval(VALID_FUNC_ID, DELAY);154 module.clearInterval(VALID_FUNC_ID);155 mLooper.idle(DELAY, TimeUnit.MILLISECONDS);156 Mockito.verify(module, never()).handleMessage(any(Message.class));157 }158 @Test159 public void setClearTimeout2(){160 module.setTimeout(NO_CACHING_FUNC_ID, DELAY);161 module.clearTimeout(NO_CACHING_FUNC_ID);162 mLooper.idle(DELAY, TimeUnit.MILLISECONDS);163 Mockito.verify(module, never()).handleMessage(any(Message.class));164 }165 @Test166 public void setClearInterval2(){167 module.setInterval(NO_CACHING_FUNC_ID, DELAY);168 module.clearInterval(NO_CACHING_FUNC_ID);169 mLooper.idle(DELAY, TimeUnit.MILLISECONDS);170 Mockito.verify(module, never()).handleMessage(any(Message.class));171 }172}...
Source:BaseStatementHandlerTest.java
...53 verifyZeroInteractions(statement); // not apply anything54 }55 @Test56 void specifyMappedStatementTimeoutOnly() throws SQLException {57 mappedStatementBuilder.timeout(10);58 BaseStatementHandler handler = new SimpleStatementHandler(null, mappedStatementBuilder.build(), null, null, null, null);59 handler.setStatementTimeout(statement, null);60 verify(statement).setQueryTimeout(10); // apply a mapped statement timeout61 }62 @Test63 void specifyDefaultTimeoutOnly() throws SQLException {64 doReturn(20).when(configuration).getDefaultStatementTimeout();65 BaseStatementHandler handler = new SimpleStatementHandler(null, mappedStatementBuilder.build(), null, null, null, null);66 handler.setStatementTimeout(statement, null);67 verify(statement).setQueryTimeout(20); // apply a default timeout68 }69 @Test70 void specifyTransactionTimeout() throws SQLException {71 BaseStatementHandler handler = new SimpleStatementHandler(null, mappedStatementBuilder.build(), null, null, null, null);72 handler.setStatementTimeout(statement, 5);73 verify(statement).setQueryTimeout(5); // apply a transaction timeout74 }75 @Test76 void specifyQueryTimeoutZeroAndTransactionTimeout() throws SQLException {77 doReturn(0).when(configuration).getDefaultStatementTimeout();78 BaseStatementHandler handler = new SimpleStatementHandler(null, mappedStatementBuilder.build(), null, null, null, null);79 handler.setStatementTimeout(statement, 5);80 verify(statement).setQueryTimeout(5); // apply a transaction timeout81 }82 @Test83 void specifyMappedStatementTimeoutAndDefaultTimeout() throws SQLException {84 doReturn(20).when(configuration).getDefaultStatementTimeout();85 mappedStatementBuilder.timeout(30);86 BaseStatementHandler handler = new SimpleStatementHandler(null, mappedStatementBuilder.build(), null, null, null, null);87 handler.setStatementTimeout(statement, null);88 verify(statement).setQueryTimeout(30); // apply a mapped statement timeout89 verify(configuration, never()).getDefaultStatementTimeout();90 }91 @Test92 void specifyQueryTimeoutAndTransactionTimeoutMinIsQueryTimeout() throws SQLException {93 doReturn(10).when(configuration).getDefaultStatementTimeout();94 BaseStatementHandler handler = new SimpleStatementHandler(null, mappedStatementBuilder.build(), null, null, null, null);95 handler.setStatementTimeout(statement, 20);96 verify(statement).setQueryTimeout(10); // apply a query timeout97 }98 @Test99 void specifyQueryTimeoutAndTransactionTimeoutMinIsTransactionTimeout() throws SQLException {100 doReturn(10).when(configuration).getDefaultStatementTimeout();101 BaseStatementHandler handler = new SimpleStatementHandler(null, mappedStatementBuilder.build(), null, null, null, null);102 handler.setStatementTimeout(statement, 5);103 verify(statement).setQueryTimeout(10);104 verify(statement).setQueryTimeout(5); // apply a transaction timeout105 }106 @Test107 void specifyQueryTimeoutAndTransactionTimeoutWithSameValue() throws SQLException {108 doReturn(10).when(configuration).getDefaultStatementTimeout();109 BaseStatementHandler handler = new SimpleStatementHandler(null, mappedStatementBuilder.build(), null, null, null, null);110 handler.setStatementTimeout(statement, 10);111 verify(statement).setQueryTimeout(10);112 }113}...
Source:ClientBeatCheckTaskTest.java
1/*2 * Copyright 1999-2018 Alibaba Group Holding Ltd.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 at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * 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 and14 * limitations under the License.15 */16package com.alibaba.nacos.naming.healthcheck;17import com.alibaba.nacos.api.naming.PreservedMetadataKeys;18import com.alibaba.nacos.naming.core.DistroMapper;19import com.alibaba.nacos.naming.core.Instance;20import com.alibaba.nacos.naming.core.Service;21import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;22import com.alibaba.nacos.naming.misc.GlobalConfig;23import com.alibaba.nacos.naming.misc.SwitchDomain;24import com.alibaba.nacos.naming.push.UdpPushService;25import com.alibaba.nacos.sys.utils.ApplicationUtils;26import org.junit.Assert;27import org.junit.Before;28import org.junit.Test;29import org.junit.runner.RunWith;30import org.mockito.InjectMocks;31import org.mockito.Mock;32import org.mockito.Mockito;33import org.mockito.Spy;34import org.mockito.junit.MockitoJUnitRunner;35import org.springframework.context.ConfigurableApplicationContext;36import org.springframework.test.util.ReflectionTestUtils;37import java.util.ArrayList;38import java.util.HashMap;39import java.util.List;40import java.util.Map;41import static org.mockito.Mockito.when;42@RunWith(MockitoJUnitRunner.class)43public class ClientBeatCheckTaskTest {44 45 @InjectMocks46 @Spy47 private ClientBeatCheckTask clientBeatCheckTask;48 49 @Mock50 private DistroMapper distroMapperSpy;51 52 @Mock53 private Service serviceSpy;54 55 @Mock56 private GlobalConfig globalConfig;57 58 @Mock59 private UdpPushService pushService;60 61 @Mock62 private SwitchDomain switchDomain;63 64 @Mock65 private UpgradeJudgement upgradeJudgement;66 67 @Mock68 private ConfigurableApplicationContext context;69 70 @Before71 public void init() {72 ReflectionTestUtils.setField(clientBeatCheckTask, "service", serviceSpy);73 Mockito.doReturn(distroMapperSpy).when(clientBeatCheckTask).getDistroMapper();74 Mockito.doReturn(globalConfig).when(clientBeatCheckTask).getGlobalConfig();75 Mockito.doReturn(pushService).when(clientBeatCheckTask).getPushService();76 Mockito.doReturn(switchDomain).when(clientBeatCheckTask).getSwitchDomain();77 ApplicationUtils.injectContext(context);78 when(context.getBean(UpgradeJudgement.class)).thenReturn(upgradeJudgement);79 }80 81 @Test82 public void testHeartBeatNotTimeout() {83 Instance instance = new Instance();84 instance.setLastBeat(System.currentTimeMillis());85 instance.setMarked(false);86 instance.setHealthy(true);87 Map<String, String> metadata = new HashMap<>();88 metadata.put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, "1000000000");89 instance.setMetadata(metadata);90 91 Mockito.doReturn("test").when(serviceSpy).getName();92 Mockito.doReturn(true).when(distroMapperSpy).responsible(Mockito.anyString());93 clientBeatCheckTask.run();94 Assert.assertTrue(instance.isHealthy());95 }96 97 @Test98 public void testHeartBeatTimeout() {99 Instance instance = new Instance();100 instance.setLastBeat(System.currentTimeMillis() - 1000);101 instance.setMarked(false);102 instance.setHealthy(true);103 Map<String, String> metadata = new HashMap<>();104 metadata.put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, "10");105 instance.setMetadata(metadata);106 List<Instance> instances = new ArrayList<>();107 instances.add(instance);108 Mockito.doReturn("test").when(serviceSpy).getName();109 Mockito.doReturn(true).when(distroMapperSpy).responsible(Mockito.anyString());110 Mockito.doReturn(true).when(switchDomain).isHealthCheckEnabled();111 112 when(serviceSpy.allIPs(true)).thenReturn(instances);113 114 clientBeatCheckTask.run();115 Assert.assertFalse(instance.isHealthy());116 }117 118 @Test119 public void testIpDeleteTimeOut() {120 Instance instance = new Instance();121 instance.setLastBeat(System.currentTimeMillis());122 instance.setMarked(true);123 instance.setHealthy(true);124 Map<String, String> metadata = new HashMap<>();125 metadata.put(PreservedMetadataKeys.IP_DELETE_TIMEOUT, "10");126 instance.setMetadata(metadata);127 Mockito.doReturn(true).when(distroMapperSpy).responsible(null);128 129 clientBeatCheckTask.run();130 }131 132 @Test133 public void testIpDeleteNotTimeOut() {134 Instance instance = new Instance();135 instance.setLastBeat(System.currentTimeMillis());136 instance.setMarked(true);137 instance.setHealthy(true);138 Map<String, String> metadata = new HashMap<>();139 metadata.put(PreservedMetadataKeys.IP_DELETE_TIMEOUT, "10000");140 instance.setMetadata(metadata);141 142 Mockito.doReturn(true).when(distroMapperSpy).responsible(null);143 144 clientBeatCheckTask.run();145 }146}...
Source:TimeoutTest.java
1/*2 * Copyright (c) 2007 Mockito contributors3 * This program is made available under the terms of the MIT License.4 */5package org.mockito.verification;67import static org.mockito.Mockito.*;89import org.junit.Test;10import org.mockito.Mock;11import org.mockito.exceptions.base.MockitoAssertionError;12import org.mockito.internal.verification.AtLeast;13import org.mockito.internal.verification.AtMost;14import org.mockito.internal.verification.Only;15import org.mockito.internal.verification.Times;16import org.mockito.internal.verification.VerificationDataImpl;17import org.mockitoutil.TestBase;1819@SuppressWarnings("unchecked")20public class TimeoutTest extends TestBase {21 22 @Mock VerificationMode mode;23 @Mock VerificationDataImpl data;24 MockitoAssertionError error = new MockitoAssertionError(""); 2526 @Test27 public void shouldPassWhenVerificationPasses() {28 Timeout t = new Timeout(1, 3, mode);29 30 doNothing().when(mode).verify(data);31 32 t.verify(data);33 }34 35 @Test36 public void shouldFailBecauseVerificationFails() {37 Timeout t = new Timeout(1, 2, mode);38 39 doThrow(error).40 doThrow(error).41 doThrow(error). 42 when(mode).verify(data);43 44 try {45 t.verify(data);46 fail();47 } catch (MockitoAssertionError e) {}48 }49 50 @Test51 public void shouldPassEvenIfFirstVerificationFails() {52 Timeout t = new Timeout(1, 2, mode);53 54 doThrow(error).55 doThrow(error).56 doNothing(). 57 when(mode).verify(data);58 59 t.verify(data);60 }6162 @Test63 public void shouldTryToVerifyCorrectNumberOfTimes() {64 Timeout t = new Timeout(1, 4, mode);65 66 doThrow(error).when(mode).verify(data);67 68 try {69 t.verify(data);70 fail();71 } catch (MockitoAssertionError e) {};72 73 verify(mode, times(5)).verify(data);74 }75 76 @Test77 public void shouldCreateCorrectType() {78 Timeout t = new Timeout(25, 50, mode);79 80 assertCorrectMode(t.atLeastOnce(), Timeout.class, 50, 25, AtLeast.class);81 assertCorrectMode(t.atLeast(5), Timeout.class, 50, 25, AtLeast.class);82 assertCorrectMode(t.times(5), Timeout.class, 50, 25, Times.class);83 assertCorrectMode(t.never(), Timeout.class, 50, 25, Times.class);84 assertCorrectMode(t.only(), Timeout.class, 50, 25, Only.class);85 }86 87 private void assertCorrectMode(VerificationMode t, Class expectedType, int expectedTimeout, int expectedTreshold, Class expectedDelegateType) {88 assertEquals(expectedType, t.getClass());89 assertEquals(expectedTimeout, ((Timeout) t).impl.getTimeout());90 assertEquals(expectedTreshold, ((Timeout) t).impl.getTreshhold());91 assertEquals(expectedDelegateType, ((Timeout) t).impl.getDelegate().getClass());92 }
...
Source:VariableTimeoutCondition_getTimeoutTest.java
1package org.nhindirect.monitor.condition.impl;2import static org.junit.Assert.assertEquals;3import static org.mockito.Matchers.any;4import static org.mockito.Matchers.eq;5import static org.mockito.Mockito.mock;6import static org.mockito.Mockito.never;7import static org.mockito.Mockito.spy;8import static org.mockito.Mockito.times;9import static org.mockito.Mockito.verify;10import static org.mockito.Mockito.when;11import java.util.ArrayList;12import java.util.Collection;13import org.junit.Test;14import org.nhindirect.common.tx.model.Tx;15import org.nhindirect.monitor.condition.TxTimeoutCondition;16public class VariableTimeoutCondition_getTimeoutTest 17{18 @SuppressWarnings("unchecked")19 @Test20 public void testGetTimeoutTest_nullMessageToTrack_assertUsesGeneralCondtion()21 {22 TxTimeoutCondition timelyCond = mock(TxTimeoutCondition.class);23 TxTimeoutCondition generalCond = mock(TxTimeoutCondition.class);24 25 VariableTimeoutCondition cond = new VariableTimeoutCondition(timelyCond, generalCond);26 VariableTimeoutCondition spy = spy(cond);27 28 when(spy.getMessageToTrack((Collection<Tx>)any())).thenReturn(null);29 30 assertEquals(0, spy.getTimeout(new ArrayList<Tx>(), 1000));31 32 verify(timelyCond, never()).getTimeout((ArrayList<Tx>)any(), eq((long)1000));33 verify(generalCond, times(1)).getTimeout((ArrayList<Tx>)any(), eq((long)1000));34 }35 36 @SuppressWarnings("unchecked")37 @Test38 public void testGetTimeoutTest_nonTimelyMessage_assertUsesGeneralCondtion()39 {40 TxTimeoutCondition timelyCond = mock(TxTimeoutCondition.class);41 TxTimeoutCondition generalCond = mock(TxTimeoutCondition.class);42 43 VariableTimeoutCondition cond = new VariableTimeoutCondition(timelyCond, generalCond);44 VariableTimeoutCondition spy = spy(cond);45 46 Tx tx = mock(Tx.class);47 48 when(spy.getMessageToTrack((Collection<Tx>)any())).thenReturn(tx);49 when(spy.isRelAndTimelyRequired((Tx)any())).thenReturn(false); 50 51 assertEquals(0, spy.getTimeout(new ArrayList<Tx>(), 1000));52 53 verify(timelyCond, never()).getTimeout((ArrayList<Tx>)any(), eq((long)1000));54 verify(generalCond, times(1)).getTimeout((ArrayList<Tx>)any(), eq((long)1000));55 }56 57 @SuppressWarnings("unchecked")58 @Test59 public void testGetTimeoutTest_timelyMessage_assertUsesTimelyCondtion()60 {61 TxTimeoutCondition timelyCond = mock(TxTimeoutCondition.class);62 TxTimeoutCondition generalCond = mock(TxTimeoutCondition.class);63 64 VariableTimeoutCondition cond = new VariableTimeoutCondition(timelyCond, generalCond);65 VariableTimeoutCondition spy = spy(cond);66 67 Tx tx = mock(Tx.class);68 69 when(spy.getMessageToTrack((Collection<Tx>)any())).thenReturn(tx);70 when(spy.isRelAndTimelyRequired((Tx)any())).thenReturn(true); 71 72 assertEquals(0, spy.getTimeout(new ArrayList<Tx>(), 1000));73 74 verify(timelyCond, times(1)).getTimeout((ArrayList<Tx>)any(), eq((long)1000));75 verify(generalCond, never()).getTimeout((ArrayList<Tx>)any(), eq((long)1000));76 }77}...
timeout
Using AI Code Generation
1import org.junit.Test;2import org.junit.runner.RunWith;3import org.mockito.Mock;4import org.mockito.junit.MockitoJUnitRunner;5import java.util.List;6import static org.junit.Assert.assertEquals;7import static org.mockito.Mockito.timeout;8import static org.mockito.Mockito.verify;9@RunWith(MockitoJUnitRunner.class)10public class MockitoTimeoutTest {11 private List<String> mockList;12 public void testTimeout() {13 mockList.add("one");14 verify(mockList, timeout(100).atLeast(1)).add("one");15 assertEquals(0, mockList.size());16 }17}18 at org.junit.Assert.fail(Assert.java:88)19 at org.junit.Assert.failNotEquals(Assert.java:834)20 at org.junit.Assert.assertEquals(Assert.java:645)21 at org.junit.Assert.assertEquals(Assert.java:631)22 at com.baeldung.mockito.MockitoTimeoutTest.testTimeout(MockitoTimeoutTest.java:21)
timeout
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.invocation.InvocationOnMock;3import org.mockito.stubbing.Answer;4public class 1 {5 public static void main(String[] args) {6 Runnable r = Mockito.mock(Runnable.class);7 Mockito.doAnswer(new Answer<Void>() {8 public Void answer(InvocationOnMock invocation) throws Throwable {9 Thread.sleep(1000);10 return null;11 }12 }).when(r).run();13 r.run();14 }15}16r.run();17-> at 1.main(1.java:13)18import org.mockito.Mockito;19public class 2 {20 public static void main(String[] args) {21 Runnable r = Mockito.mock(Runnable.class);22 Mockito.doNothing().when(r).run();23 r.run();24 }25}
timeout
Using AI Code Generation
1package org.kodejava.example.mockito;2import org.junit.Test;3import org.mockito.Mockito;4import java.util.concurrent.TimeUnit;5public class TimeoutExample {6 public void testTimeout() throws Exception {7 Runnable runnable = Mockito.mock(Runnable.class);8 Mockito.timeout(1000).doNothing().when(runnable).run();9 runnable.run();10 TimeUnit.MILLISECONDS.sleep(2000);11 }12}13java.lang.RuntimeException: Method call runnable.run() expected 1 time(s), but was 0. Last 1 interactions:14runnable.run();15 at org.mockito.exceptions.verification.TooLittleActualInvocations.create(TooLittleActualInvocations.java:25)16 at org.mockito.exceptions.verification.TooLittleActualInvocations.create(TooLittleActualInvocations.java:10)17 at org.mockito.internal.verification.Times.verify(Times.java:32)18 at org.mockito.internal.verification.VerificationModeFactory$1.verify(VerificationModeFactory.java:26)19 at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:93)20 at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)21 at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:35)22 at org.mockito.internal.creation.cglib.MethodInterceptorFilter.intercept(MethodInterceptorFilter.java:59)23 at org.kodejava.example.mockito.TimeoutExample$1.run(TimeoutExample.java:15)24 at org.kodejava.example.mockito.TimeoutExample.testTimeout(TimeoutExample.java:21)
timeout
Using AI Code Generation
1import static org.mockito.Mockito.*;2import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;3import org.junit.Test;4import org.junit.runner.RunWith;5import org.mockito.runners.MockitoJUnitRunner;6@RunWith(MockitoJUnitRunner.class)7public class MockitoTimeoutTest {8 public void testMockitoTimeout() throws Exception {9 Runnable runnable = mock(Runnable.class);10 doThrow(new RuntimeException("Exception")).when(runnable).run();11 try {12 timeout(100).verify(runnable).run();13 } catch (ArgumentsAreDifferent e) {14 System.out.println("Exception caught");15 }16 }17}
timeout
Using AI Code Generation
1import java.util.concurrent.TimeUnit;2import static org.mockito.Mockito.*;3public class 1 {4 public static void main(String[] args) {5 List mockList = mock(List.class);6 verify(mockList, timeout(100)).add("one");7 verify(mockList, timeout(100).times(1)).add("one");8 verify(mockList, timeout(100)).add("two");9 verify(mockList, timeout(100).times(1)).add("two");10 verify(mockList, timeout(100).times(2)).add("three");11 verify(mockList, timeout(100).times(2)).add("two");12 verify(mockList, never()).add("three");13 verify(mockList, atLeastOnce()).add("three");14 verify(mockList, atLeast(2)).add("five");15 verify(mockList, atMost(5)).add("three");16 }17}18list.add("three");19-> at 1.main(1.java:13)20list.add("two");21-> at 1.main(1.java:9)22list.add("two");23-> at 1.main(1.java:10)24list.add("three");25-> at 1.main(1.java:12)26list.add("three");27-> at 1.main(1.java:14)28list.add("five");29-> at 1.main(1.java:15)30list.add("five");31-> at 1.main(1.java:16)32list.add("five");33-> at 1.main(1.java:17)34list.add("five");35-> at 1.main(1.java:18)36list.add("five");37-> at 1.main(1.java:19)38list.add("five");39-> at 1.main(1.java:20)40list.add("five");41-> at 1.main(1.java:21)42list.add("five");43-> at 1.main(1.java:22)44list.add("five
timeout
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.invocation.InvocationOnMock;3import org.mockito.stubbing.Answer;4public class 1 {5 public static void main(String[] args) {6 Answer answer = Mockito.mock(Answer.class);7 Mockito.when(answer.answer(Mockito.any(InvocationOnMock.class))).thenCallRealMethod().timeout(1000);8 }9}10 when(mock.getArticles()).thenReturn(articles);11 at org.mockito.internal.invocation.StubbedInvocationMatcher.answer(StubbedInvocationMatcher.java:34)12 at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:93)13 at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)14 at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38)15 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:62)16 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptSuperCallable(MockMethodInterceptor.java:109)17 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptSuperCallable(MockMethodInterceptor.java:100)18 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.handle(MockMethodInterceptor.java:56)19 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:50)20 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptSuperCallable(MockMethodInterceptor.java:109)21 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptSuperCallable(MockMethodInterceptor.java:100)22 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.handle(MockMethodInterceptor.java:56)
timeout
Using AI Code Generation
1package com.ack.j2se.mock;2import static org.mockito.Mockito.timeout;3import static org.mockito.Mockito.verify;4import java.util.List;5import org.junit.Test;6public class TestMockitoTimeout {7public void test() {8List mockedList = Mockito.mock(List.class);9mockedList.add("one");10mockedList.clear();11verify(mockedList).add("one");12verify(mockedList, times(1)).add("one");13verify(mockedList, times(2)).clear();14verify(mockedList, timeout(100)).add("one");15verify(mockedList, timeout(100).times(2)).clear();16verify(mockedList, never()).add("two");17verify(mockedList, atLeastOnce()).add("one");18verify(mockedList, atLeast(2)).add("one");19verify(mockedList, atMost(5)).add("one");20}21}22List.add("one");23-> at com.ack.j2se.mock.TestMockitoTimeout.test(TestMockitoTimeout.java:32)24-> at com.ack.j2se.mock.TestMockitoTimeout.test(TestMockitoTimeout.java:32)25at com.ack.j2se.mock.TestMockitoTimeout.test(TestMockitoTimeout.java:32)
timeout
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.exceptions.base.MockitoException;3import java.util.concurrent.TimeUnit;4import static org.mockito.Mockito.when;5import static org.mockito.Mockito.mock;6import static org.mockito.Mockito.timeout;7import java.util.concurrent.TimeUnit;8class Test{9 public static void main(String[] args) {10 TestInterface test = mock(TestInterface.class);11 when(test.getUniqueId()).thenReturn(43);12 when(test.getUniqueId()).thenReturn(43).timeout(10, TimeUnit.MILLISECONDS);13 verify(test, timeout(10)).getUniqueId();14 verify(test, timeout(10).times(1)).getUniqueId();15 verify(test, timeout(10).atLeastOnce()).getUniqueId();16 verify(test, timeout(10).atMost(2)).getUniqueId();17 }18}19interface TestInterface{20 public int getUniqueId();21}22Cannot use timeout() on a void method!23 at org.mockito.internal.invocation.RealMethod$FromVoidMethod.<init>(RealMethod.java:39)24 at org.mockito.internal.invocation.RealMethod.fromVoidMethod(RealMethod.java:34)25 at org.mockito.internal.invocation.InvocationImpl.<init>(InvocationImpl.java:41)26 at org.mockito.internal.invocation.InvocationBuilder.build(InvocationBuilder.java:18)27 at org.mockito.internal.invocation.InvocationMatcher.<init>(InvocationMatcher.java:35)28 at org.mockito.internal.invocation.InvocationMatcher.create(InvocationMatcher.java:27)29 at org.mockito.internal.invocation.InvocationMatcher.create(InvocationMatcher.java:22)30 at org.mockito.internal.progress.MockingProgressImpl.validateState(MockingProgressImpl.java:63)31 at org.mockito.internal.progress.ThreadSafeMockingProgress.validateState(ThreadSafeMockingProgress.java:47)32 at org.mockito.internal.verification.api.VerificationDataImpl.<init>(VerificationDataImpl.java:41)33 at org.mockito.internal.verification.api.VerificationDataImpl.<init>(VerificationDataImpl.java:34)34 at org.mockito.internal.verification.VerificationModeFactory.timeout(VerificationModeFactory.java:87)35 at Test.main(Test.java:19)
timeout
Using AI Code Generation
1package mypack;2import java.util.concurrent.TimeUnit;3import java.util.concurrent.TimeoutException;4import org.mockito.Mockito;5public class TimeoutExample {6 public static void main(String[] args) throws TimeoutException {7 MockClass mockObj = Mockito.mock(MockClass.class);8 Mockito.withSettings().timeout(100, TimeUnit.MILLISECONDS);9 mockObj.myMethod();10 }11}12class MockClass {13 public void myMethod() {14 try {15 Thread.sleep(1000);16 } catch (InterruptedException e) {17 e.printStackTrace();18 }19 }20}
timeout
Using AI Code Generation
1import org.mockito.Mockito;2class Test {3 public static void main(String[] args) {4 Test t = Mockito.mock(Test.class);5 Mockito.verify(t, Mockito.timeout(100)).add(10, 20);6 }7 public int add(int a, int b) {8 return a + b;9 }10}11test.add(12);13-> at Test.main(Test.java:10)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!