Best Mockito code snippet using org.mockito.Spy.release
Source:ZookeeperDistributedLockTest.java  
...114        } catch (Exception e) {115            // ZkPeekLockInterruptException expected116            assertTrue(e instanceof ZkPeekLockInterruptException);117        }118        // should release lock119        Mockito.reset(spy);120        assertFalse(lock.isLocked(path));121    }122    @Test123    public void testTwoClientLockWhenCatchInterruptException() {124        String path = ZK_PFX + "/test_interrupt_lock";125        DistributedLock lock1 = factory.lockForClient("client_1");126        DistributedLock lock2 = factory.lockForClient("client_2");127        assertFalse(lock1.isLocked(path));128        assertFalse(lock2.isLocked(path));129        // lock first by client_1130        assertTrue(lock1.lock(path));131        assertFalse(lock2.lock(path));132        assertTrue(lock1.isLockedByMe(path));133        assertFalse(lock2.isLockedByMe(path));134        // mock lock for client_2 to simulate lock when an InterruptException caught135        DistributedLock spy2 = Mockito.spy(lock2);136        // mock interruptException when peekLock only once137        Mockito.doThrow(new ZkPeekLockInterruptException("mock interrupt")).doCallRealMethod().when(spy2)138                .peekLock(Mockito.anyString());139        try {140            spy2.lock(path);141            fail("should throw exception");142        } catch (Exception e) {143            // ZkPeekLockInterruptException expected144            assertTrue(e instanceof ZkPeekLockInterruptException);145        }146        // should not release lock because lock was held by client_1147        Mockito.reset(spy2);148        assertTrue(lock1.isLocked(path));149        assertTrue(lock2.isLocked(path));150        assertTrue(lock1.isLockedByMe(path));151        assertFalse(lock2.isLockedByMe(path));152        // mock lock for client_1 to simulate lock when an InterruptException caught153        DistributedLock spy1 = Mockito.spy(lock1);154        // mock interruptException when peekLock only once155        Mockito.doThrow(new ZkPeekLockInterruptException("mock interrupt")).doCallRealMethod().when(spy1)156                .peekLock(Mockito.anyString());157        try {158            spy1.lock(path);159            fail("should throw exception");160        } catch (Exception e) {161            // ZkPeekLockInterruptException expected162            assertTrue(e instanceof ZkPeekLockInterruptException);163        }164        // should release lock because lock was held by client_1165        Mockito.reset(spy1);166        assertFalse(lock1.isLocked(path));167        assertFalse(lock2.isLocked(path));168        assertFalse(lock1.isLockedByMe(path));169        assertFalse(lock2.isLockedByMe(path));170    }171    @Test172    public void testSingleClientUnlockWhenCatchInterruptExceptionOnPeekLock() {173        String path = ZK_PFX + "/test_interrupt_lock";174        DistributedLock lock = factory.lockForClient("client");175        assertFalse(lock.isLocked(path));176        assertTrue(lock.lock(path));177        assertTrue(lock.isLocked(path));178        assertTrue(lock.isLockedByMe(path));179        DistributedLock spy = Mockito.spy(lock);180        // mock interruptException when peekLock only once181        Mockito.doThrow(new ZkPeekLockInterruptException("mock interrupt")).doCallRealMethod().when(spy)182                .peekLock(Mockito.anyString());183        try {184            spy.unlock(path);185            fail("should throw exception");186        } catch (Exception e) {187            // ZkPeekLockInterruptException expected188            assertTrue(e instanceof ZkPeekLockInterruptException);189        }190        // should release lock191        Mockito.reset(spy);192        assertFalse(lock.isLocked(path));193    }194    @Test195    public void testTwoClientUnlockWhenCatchInterruptExceptionOnPeekLock() {196        String path = ZK_PFX + "/test_interrupt_lock";197        DistributedLock lock1 = factory.lockForClient("client_1");198        DistributedLock lock2 = factory.lockForClient("client_2");199        assertFalse(lock1.isLocked(path));200        assertFalse(lock2.isLocked(path));201        // lock first by client_1202        assertTrue(lock1.lock(path));203        assertFalse(lock2.lock(path));204        assertTrue(lock1.isLockedByMe(path));205        assertFalse(lock2.isLockedByMe(path));206        // mock lock for client_2 to simulate lock when an InterruptException caught207        DistributedLock spy2 = Mockito.spy(lock2);208        // mock interruptException when peekLock only once209        Mockito.doThrow(new ZkPeekLockInterruptException("mock interrupt")).doCallRealMethod().when(spy2)210                .peekLock(Mockito.anyString());211        try {212            spy2.unlock(path);213            fail("should throw exception");214        } catch (Exception e) {215            // ZkReleaseLockException expected: lock was held by client_1216            assertTrue(e instanceof ZkReleaseLockException);217        }218        // should not release lock because lock was held by client_1219        Mockito.reset(spy2);220        assertTrue(lock1.isLocked(path));221        assertTrue(lock2.isLocked(path));222        assertTrue(lock1.isLockedByMe(path));223        assertFalse(lock2.isLockedByMe(path));224        // mock lock for client_1 to simulate lock when an InterruptException caught225        DistributedLock spy1 = Mockito.spy(lock1);226        // mock interruptException when peekLock only once227        Mockito.doThrow(new ZkPeekLockInterruptException("mock interrupt")).doCallRealMethod().when(spy1)228                .peekLock(Mockito.anyString());229        try {230            spy1.unlock(path);231            fail("should throw exception");232        } catch (Exception e) {233            // ZkPeekLockInterruptException expected234            assertTrue(e instanceof ZkPeekLockInterruptException);235        }236        // should release lock because lock was held by client_1237        Mockito.reset(spy1);238        assertFalse(lock1.isLocked(path));239        assertFalse(lock2.isLocked(path));240        assertFalse(lock1.isLockedByMe(path));241        assertFalse(lock2.isLockedByMe(path));242    }243    @Test244    public void testSingleClientUnlockWhenCatchInterruptExceptionOnPurgeLock() {245        String path = ZK_PFX + "/test_interrupt_lock";246        ZookeeperDistributedLock lock = (ZookeeperDistributedLock) factory.lockForClient("client");247        assertFalse(lock.isLocked(path));248        assertTrue(lock.lock(path));249        assertTrue(lock.isLocked(path));250        assertTrue(lock.isLockedByMe(path));251        ZookeeperDistributedLock spy = Mockito.spy(lock);252        // mock interruptException when purgeLock only once253        Mockito.doThrow(new ZkReleaseLockInterruptException("mock interrupt")).doCallRealMethod().when(spy)254                .purgeLockInternal(Mockito.anyString());255        try {256            spy.unlock(path);257            fail("should throw exception");258        } catch (Exception e) {259            // ZkPeekLockInterruptException expected260            assertTrue(e instanceof ZkReleaseLockInterruptException);261        }262        // should release lock263        Mockito.reset(spy);264        assertFalse(lock.isLocked(path));265    }266    @Test267    public void testTwoClientUnlockWhenCatchInterruptExceptionOnPurgeLock() {268        String path = ZK_PFX + "/test_interrupt_lock";269        ZookeeperDistributedLock lock1 = (ZookeeperDistributedLock) factory.lockForClient("client_1");270        ZookeeperDistributedLock lock2 = (ZookeeperDistributedLock) factory.lockForClient("client_2");271        assertFalse(lock1.isLocked(path));272        assertFalse(lock2.isLocked(path));273        // lock first by client_1274        assertTrue(lock1.lock(path));275        assertFalse(lock2.lock(path));276        assertTrue(lock1.isLockedByMe(path));277        assertFalse(lock2.isLockedByMe(path));278        // mock lock for client_2 to simulate lock when an InterruptException caught279        ZookeeperDistributedLock spy2 = Mockito.spy(lock2);280        // mock interruptException when purgeLock only once281        Mockito.doThrow(new ZkReleaseLockInterruptException("mock interrupt")).doCallRealMethod().when(spy2)282                .purgeLockInternal(Mockito.anyString());283        try {284            spy2.unlock(path);285            fail("should throw exception");286        } catch (Exception e) {287            // ZkReleaseLockException expected: lock was held by client_1288            assertTrue(e instanceof ZkReleaseLockException);289        }290        // should not release lock because lock was held by client_1291        Mockito.reset(spy2);292        assertTrue(lock1.isLocked(path));293        assertTrue(lock2.isLocked(path));294        assertTrue(lock1.isLockedByMe(path));295        assertFalse(lock2.isLockedByMe(path));296        // mock lock for client_1 to simulate lock when an InterruptException caught297        ZookeeperDistributedLock spy1 = Mockito.spy(lock1);298        // mock interruptException when purgeLock only once299        Mockito.doThrow(new ZkReleaseLockInterruptException("mock interrupt")).doCallRealMethod().when(spy1)300                .purgeLockInternal(Mockito.anyString());301        try {302            spy1.unlock(path);303            fail("should throw exception");304        } catch (Exception e) {305            // ZkPeekLockInterruptException expected306            assertTrue(e instanceof ZkReleaseLockInterruptException);307        }308        // should release lock because lock was held by client_1309        Mockito.reset(spy1);310        assertFalse(lock1.isLocked(path));311        assertFalse(lock2.isLocked(path));312        assertFalse(lock1.isLockedByMe(path));313        assertFalse(lock2.isLockedByMe(path));314    }315}...Source:ReleaseSegmentOnHistoricalRebalanceTest.java  
...41import static org.mockito.Mockito.doAnswer;42import static org.mockito.Mockito.spy;43import static org.mockito.Mockito.when;44/**45 * Testing the release of WAL segments during historical rebalance.46 */47@WithSystemProperty(key = IGNITE_PDS_WAL_REBALANCE_THRESHOLD, value = "0")48public class ReleaseSegmentOnHistoricalRebalanceTest extends AbstractReleaseSegmentTest {49    /**50     * Checks that if release the segment after {@link CheckpointHistory#searchAndReserveCheckpoints},51     * there will be no errors and the rebalance will be completed.52     *53     * @throws Exception If failed.54     */55    @Test56    public void testReleaseSegmentAfterSearchAndReserveCheckpoints() throws Exception {57        checkHistoricalRebalance(n -> {58            CheckpointHistory spy = spy(dbMgr(n).checkpointHistory());59            when(spy.searchAndReserveCheckpoints(any())).thenAnswer(m -> {60                CheckpointHistoryResult res = (CheckpointHistoryResult)m.callRealMethod();61                WALPointer reserved = res.reservedCheckpointMark();62                assertNotNull(reserved);63                release(n, reserved);64                return res;65            });66            checkpointHistory(n, spy);67        });68    }69    /**70     * Checks that if release the segment before {@link GridCacheDatabaseSharedManager#releaseHistoryForExchange},71     * there will be no errors and the rebalance will be completed.72     *73     * @throws Exception If failed.74     */75    @Test76    public void testReleaseBeforeReleaseHistoryForExchange() throws Exception {77        checkHistoricalRebalance(n -> {78            GridCacheDatabaseSharedManager spy = spy(dbMgr(n));79            doAnswer(m -> {80                release(n, getFieldValue(spy, "reservedForExchange"));81                return m.callRealMethod();82            }).when(spy).releaseHistoryForExchange();83            databaseManager(n, spy);84        });85    }86    /**87     * Checks that if there is no segment reservation in {@link GridCacheDatabaseSharedManager#reserveHistoryForPreloading},88     * there will be no errors and the rebalance will be completed.89     *90     * @throws Exception If failed.91     */92    @Test93    public void testNoReserveHistoryForPreloading() throws Exception {94        checkHistoricalRebalance(n -> {95            GridCacheDatabaseSharedManager spy = spy(dbMgr(n));96            when(spy.reserveHistoryForPreloading(any())).thenAnswer(m -> false);97            databaseManager(n, spy);98        });99    }100    /**101     * Checks that if release the segment before {@link GridCacheDatabaseSharedManager#releaseHistoryForPreloading},102     * there will be no errors and the rebalance will be completed.103     *104     * @throws Exception If failed.105     */106    @Test107    public void testReleaseBeforeReleaseHistoryForPreloading() throws Exception {108        checkHistoricalRebalance(n -> {109            GridCacheDatabaseSharedManager spy = spy(dbMgr(n));110            doAnswer(m -> {111                release(n, spy.latestWalPointerReservedForPreloading());112                return m.callRealMethod();113            }).when(spy).releaseHistoryForPreloading();114            databaseManager(n, spy);115        });116    }117    /**118     * Checks that if release the segment before {@link IgniteCacheOffheapManagerImpl#rebalanceIterator},119     * there will be no errors and the rebalance will be completed.120     *121     * @throws Exception If failed.122     */123    @Test124    public void testReleaseBeforeRebalanceIterator() throws Exception {125        checkHistoricalRebalance(n -> {126            IgniteInternalCache<?, ?> cachex = n.cachex(DEFAULT_CACHE_NAME);127            GridCacheOffheapManager spy = spy(offheapManager(cachex));128            doAnswer(m -> {129                CheckpointHistory cpHist = dbMgr(n).checkpointHistory();130                for (Long cp : cpHist.checkpoints())131                    release(n, entry(cpHist, cp).checkpointMark());132                return m.callRealMethod();133            }).when(spy).rebalanceIterator(any(), any());134            offheapManager(cachex, spy);135        });136    }137    /**138     * Checks that if release the segment during {@link IgniteCacheOffheapManagerImpl#rebalanceIterator},139     * there will be no errors and the rebalance will be completed.140     *141     * @throws Exception If failed.142     */143    @Test144    public void testReleaseDuringRebalanceIterator() throws Exception {145        checkHistoricalRebalance(n -> {146            IgniteInternalCache<?, ?> cachex = n.cachex(DEFAULT_CACHE_NAME);147            GridCacheOffheapManager spy = spy(offheapManager(cachex));148            doAnswer(m -> {149                WALPointer reserved = dbMgr(n).latestWalPointerReservedForPreloading();150                assertNotNull(reserved);151                Object o = m.callRealMethod();152                release(n, reserved);153                assertTrue(segmentAware(n).minReserveIndex(Long.MAX_VALUE));154                return o;155            }).when(spy).rebalanceIterator(any(), any());156            offheapManager(cachex, spy);157        });158    }159    /**160     * Checks that if the reservation is released immediately,161     * there will be no errors and the rebalance will be completed.162     *163     * @throws Exception If failed.164     */165    @Test166    public void testImmediateReleaseSegment() throws Exception {167        checkHistoricalRebalance(n -> {168            SegmentAware spy = spy(segmentAware(n));169            doAnswer(m -> {170                Object o = m.callRealMethod();171                spy.release(m.getArgument(0));172                return o;173            }).when(spy).reserve(anyLong());174            segmentAware(n, spy);175        });176    }177    /**178     * Checks that that if there is no reservation,179     * there will be no errors and the rebalance will be completed.180     *181     * @throws Exception If failed.182     */183    @Test184    public void testNoReserveSegment() throws Exception {185        checkHistoricalRebalance(n -> {...Source:PacketInRateLimiterTest.java  
...61        rateLimiter.drainLowWaterMark();62        Assert.assertEquals(4, rateLimiter.getOccupiedPermits());63        Assert.assertTrue(rateLimiter.isLimited());64        caOrdered.verify(connectionAdapter).setPacketInFiltering(true);65        // release 1 permit ->  3 occupied but threshold = 2 -> stay limited66        rateLimiter.releasePermit();67        Assert.assertEquals(3, rateLimiter.getOccupiedPermits());68        Assert.assertTrue(rateLimiter.isLimited());69        // release 1 permit ->  2 occupied but threshold = 2 -> escape limit70        rateLimiter.releasePermit();71        Assert.assertEquals(2, rateLimiter.getOccupiedPermits());72        Assert.assertFalse(rateLimiter.isLimited());73        caOrdered.verify(connectionAdapter).setPacketInFiltering(false);74        // lwm is reset75        acquirePermits(4);76        Assert.assertEquals(6, rateLimiter.getOccupiedPermits());77        Assert.assertFalse(rateLimiter.isLimited());78        Mockito.verify(connectionAdapter, Mockito.times(2)).setPacketInFiltering(Matchers.anyBoolean());79    }80    private void acquirePermits(int permits) {81        for (int i = 0; i < permits; i++) {82            final boolean gainedPermit = rateLimiter.acquirePermit();83            if (!gainedPermit) {84                throw new IllegalStateException("not enough permits");85            }86        }87    }88    private void releasePermits(int permits) {89        for (int i = 0; i < permits; i++) {90            rateLimiter.releasePermit();91        }92    }93    @Test94    public void testAcquirePermit() throws Exception {95        Assert.assertEquals(0, rateLimiter.getOccupiedPermits());96        Assert.assertFalse(rateLimiter.isLimited());97        // approach hwm98        acquirePermits(10);99        Assert.assertEquals(10, rateLimiter.getOccupiedPermits());100        Assert.assertFalse(rateLimiter.isLimited());101        // hit hwm102        Assert.assertFalse(rateLimiter.acquirePermit());103        Assert.assertEquals(10, rateLimiter.getOccupiedPermits());104        Assert.assertTrue(rateLimiter.isLimited());105        caOrdered.verify(connectionAdapter).setPacketInFiltering(true);106        // approach lwm107        releasePermits(5);108        Assert.assertEquals(5, rateLimiter.getOccupiedPermits());109        Assert.assertTrue(rateLimiter.isLimited());110        // cross lwm111        rateLimiter.releasePermit();112        Assert.assertEquals(4, rateLimiter.getOccupiedPermits());113        Assert.assertFalse(rateLimiter.isLimited());114        caOrdered.verify(connectionAdapter).setPacketInFiltering(false);115        Mockito.verify(connectionAdapter, Mockito.times(2)).setPacketInFiltering(Matchers.anyBoolean());116    }117    @Test118    public void testChangeWaterMarks1() throws Exception {119        rateLimiter.changeWaterMarks(2, 4);120        acquirePermits(4);121        Assert.assertEquals(4, rateLimiter.getOccupiedPermits());122        Assert.assertFalse(rateLimiter.isLimited());123        // hit hwm124        Assert.assertFalse(rateLimiter.acquirePermit());125        Assert.assertEquals(4, rateLimiter.getOccupiedPermits());126        Assert.assertTrue(rateLimiter.isLimited());127        caOrdered.verify(connectionAdapter).setPacketInFiltering(true);128        // approach lwm129        rateLimiter.releasePermit();130        Assert.assertEquals(3, rateLimiter.getOccupiedPermits());131        Assert.assertTrue(rateLimiter.isLimited());132        // cross lwm, escape limit133        rateLimiter.releasePermit();134        Assert.assertEquals(2, rateLimiter.getOccupiedPermits());135        Assert.assertFalse(rateLimiter.isLimited());136        caOrdered.verify(connectionAdapter).setPacketInFiltering(false);137        Mockito.verify(connectionAdapter, Mockito.times(2)).setPacketInFiltering(Matchers.anyBoolean());138    }139    @Test140    public void testChangeWaterMarks2() throws Exception {141        // draining to lwm/occupied = 3/6142        acquirePermits(6);143        rateLimiter.drainLowWaterMark();144        Assert.assertEquals(6, rateLimiter.getOccupiedPermits());145        Assert.assertTrue(rateLimiter.isLimited());146        caOrdered.verify(connectionAdapter).setPacketInFiltering(true);147        rateLimiter.changeWaterMarks(7, 12);148        Assert.assertEquals(6, rateLimiter.getOccupiedPermits());149        Assert.assertTrue(rateLimiter.isLimited());150        // new lwm is equal to current occupied permits - we can acquire more but flow is still limited151        acquirePermits(1);152        Assert.assertTrue(rateLimiter.isLimited());153        Assert.assertEquals(7, rateLimiter.getOccupiedPermits());154        // cross lwm, escape old lwm limit, reset lwm155        rateLimiter.releasePermit();156        Assert.assertEquals(6, rateLimiter.getOccupiedPermits());157        Assert.assertFalse(rateLimiter.isLimited());158        caOrdered.verify(connectionAdapter).setPacketInFiltering(false);159        // free to reach hwm of 12160        acquirePermits(6);161        Assert.assertEquals(12, rateLimiter.getOccupiedPermits());162        Assert.assertFalse(rateLimiter.isLimited());163        Mockito.verify(connectionAdapter, Mockito.times(2)).setPacketInFiltering(Matchers.anyBoolean());164    }165}...Source:SpringSecurityCoreVersionTests.java  
1/*2 * Copyright 2002-2013 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 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 org.springframework.security.core;17import static org.assertj.core.api.Assertions.assertThat;18import static org.mockito.Matchers.any;19import static org.mockito.Mockito.never;20import static org.mockito.Mockito.times;21import static org.mockito.Mockito.verify;22import static org.mockito.Mockito.verifyZeroInteractions;23import static org.powermock.api.mockito.PowerMockito.doReturn;24import static org.powermock.api.mockito.PowerMockito.spy;25import org.apache.commons.logging.Log;26import org.junit.After;27import org.junit.Before;28import org.junit.Test;29import org.junit.runner.RunWith;30import org.mockito.Mock;31import org.powermock.core.classloader.annotations.PrepareForTest;32import org.powermock.modules.junit4.PowerMockRunner;33import org.powermock.reflect.Whitebox;34import org.springframework.core.SpringVersion;35/**36 * Checks that the embedded version information is up to date.37 *38 * @author Luke Taylor39 * @author Rob Winch40 */41@RunWith(PowerMockRunner.class)42@PrepareForTest({ SpringSecurityCoreVersion.class, SpringVersion.class })43public class SpringSecurityCoreVersionTests {44	@Mock45	private Log logger;46	@Before47	public void setup() {48		Whitebox.setInternalState(SpringSecurityCoreVersion.class, logger);49	}50	@After51	public void cleanup() throws Exception {52		System.clearProperty(getDisableChecksProperty());53	}54	@Test55	public void springVersionIsUpToDate() throws Exception {56		// Property is set by the build script57		String springVersion = System.getProperty("springVersion");58		assertThat(SpringSecurityCoreVersion.MIN_SPRING_VERSION).isEqualTo(springVersion);59	}60	@Test61	public void serialVersionMajorAndMinorVersionMatchBuildVersion() throws Exception {62		String version = System.getProperty("springSecurityVersion");63		// Strip patch version64		String serialVersion = String.valueOf(65				SpringSecurityCoreVersion.SERIAL_VERSION_UID).substring(0, 2);66		assertThat(serialVersion.charAt(0)).isEqualTo(version.charAt(0));67		assertThat(serialVersion.charAt(1)).isEqualTo(version.charAt(2));68	}69	// SEC-229570	@Test71	public void noLoggingIfVersionsAreEqual() throws Exception {72		String version = "1";73		spy(SpringSecurityCoreVersion.class);74		spy(SpringVersion.class);75		doReturn(version).when(SpringSecurityCoreVersion.class, "getVersion");76		doReturn(version).when(SpringVersion.class, "getVersion");77		performChecks();78		verifyZeroInteractions(logger);79	}80	@Test81	public void noLoggingIfSpringVersionNull() throws Exception {82		spy(SpringSecurityCoreVersion.class);83		spy(SpringVersion.class);84		doReturn("1").when(SpringSecurityCoreVersion.class, "getVersion");85		doReturn(null).when(SpringVersion.class, "getVersion");86		performChecks();87		verifyZeroInteractions(logger);88	}89	@Test90	public void warnIfSpringVersionTooSmall() throws Exception {91		spy(SpringSecurityCoreVersion.class);92		spy(SpringVersion.class);93		doReturn("3").when(SpringSecurityCoreVersion.class, "getVersion");94		doReturn("2").when(SpringVersion.class, "getVersion");95		performChecks();96		verify(logger, times(1)).warn(any());97	}98	@Test99	public void noWarnIfSpringVersionLarger() throws Exception {100		spy(SpringSecurityCoreVersion.class);101		spy(SpringVersion.class);102		doReturn("4.0.0.RELEASE").when(SpringSecurityCoreVersion.class, "getVersion");103		doReturn("4.0.0.RELEASE").when(SpringVersion.class, "getVersion");104		performChecks();105		verify(logger, never()).warn(any());106	}107	// SEC-2697108	@Test109	public void noWarnIfSpringPatchVersionDoubleDigits() throws Exception {110		String minSpringVersion = "3.2.8.RELEASE";111		spy(SpringSecurityCoreVersion.class);112		spy(SpringVersion.class);113		doReturn("3.2.0.RELEASE").when(SpringSecurityCoreVersion.class, "getVersion");114		doReturn("3.2.10.RELEASE").when(SpringVersion.class, "getVersion");115		performChecks(minSpringVersion);116		verify(logger, never()).warn(any());117	}118	@Test119	public void noLoggingIfPropertySet() throws Exception {120		spy(SpringSecurityCoreVersion.class);121		spy(SpringVersion.class);122		doReturn("3").when(SpringSecurityCoreVersion.class, "getVersion");123		doReturn("2").when(SpringVersion.class, "getVersion");124		System.setProperty(getDisableChecksProperty(), Boolean.TRUE.toString());125		performChecks();126		verifyZeroInteractions(logger);127	}128	private String getDisableChecksProperty() throws Exception {129		return SpringSecurityCoreVersion.class.getName().concat(".DISABLE_CHECKS");130	}131	private void performChecks() throws Exception {132		Whitebox.invokeMethod(SpringSecurityCoreVersion.class, "performVersionChecks");133	}134	private void performChecks(String minSpringVersion) throws Exception {135		Whitebox.invokeMethod(SpringSecurityCoreVersion.class, "performVersionChecks",136				minSpringVersion);137	}138}...Source:OneForOneStreamManagerSuite.java  
...27public class OneForOneStreamManagerSuite {28  List<ManagedBuffer> managedBuffersToRelease = new ArrayList<>();29  @After30  public void tearDown() {31    managedBuffersToRelease.forEach(managedBuffer -> managedBuffer.release());32    managedBuffersToRelease.clear();33  }34  private ManagedBuffer getChunk(OneForOneStreamManager manager, long streamId, int chunkIndex) {35    ManagedBuffer chunk = manager.getChunk(streamId, chunkIndex);36    if (chunk != null) {37      managedBuffersToRelease.add(chunk);38    }39    return chunk;40  }41  @Test42  public void testMissingChunk() {43    OneForOneStreamManager manager = new OneForOneStreamManager();44    List<ManagedBuffer> buffers = new ArrayList<>();45    TestManagedBuffer buffer1 = Mockito.spy(new TestManagedBuffer(10));46    TestManagedBuffer buffer2 = Mockito.spy(new TestManagedBuffer(20));47    TestManagedBuffer buffer3 = Mockito.spy(new TestManagedBuffer(20));48    buffers.add(buffer1);49    // the nulls here are to simulate a file which goes missing before being read,50    // just as a defensive measure51    buffers.add(null);52    buffers.add(buffer2);53    buffers.add(null);54    buffers.add(buffer3);55    Channel dummyChannel = Mockito.mock(Channel.class, Mockito.RETURNS_SMART_NULLS);56    long streamId = manager.registerStream("appId", buffers.iterator(), dummyChannel);57    Assert.assertEquals(1, manager.numStreamStates());58    Assert.assertNotNull(getChunk(manager, streamId, 0));59    Assert.assertNull(getChunk(manager, streamId, 1));60    Assert.assertNotNull(getChunk(manager, streamId, 2));61    manager.connectionTerminated(dummyChannel);62    // loaded buffers are not released yet as in production a MangedBuffer returned by getChunk()63    // would only be released by Netty after it is written to the network64    Mockito.verify(buffer1, Mockito.never()).release();65    Mockito.verify(buffer2, Mockito.never()).release();66    Mockito.verify(buffer3, Mockito.times(1)).release();67  }68  @Test69  public void managedBuffersAreFreedWhenConnectionIsClosed() {70    OneForOneStreamManager manager = new OneForOneStreamManager();71    List<ManagedBuffer> buffers = new ArrayList<>();72    TestManagedBuffer buffer1 = Mockito.spy(new TestManagedBuffer(10));73    TestManagedBuffer buffer2 = Mockito.spy(new TestManagedBuffer(20));74    buffers.add(buffer1);75    buffers.add(buffer2);76    Channel dummyChannel = Mockito.mock(Channel.class, Mockito.RETURNS_SMART_NULLS);77    manager.registerStream("appId", buffers.iterator(), dummyChannel);78    Assert.assertEquals(1, manager.numStreamStates());79    manager.connectionTerminated(dummyChannel);80    Mockito.verify(buffer1, Mockito.times(1)).release();81    Mockito.verify(buffer2, Mockito.times(1)).release();82    Assert.assertEquals(0, manager.numStreamStates());83  }84}...Source:TestLeaseManager.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, software13 * 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 and16 * limitations under the License.17 */18package org.apache.hadoop.hdfs.server.namenode;19import junit.framework.TestCase;20import org.apache.commons.logging.Log;21import org.apache.commons.logging.LogFactory;22import org.apache.hadoop.conf.Configuration;23import org.apache.hadoop.fs.Path;24import org.apache.hadoop.hdfs.DistributedFileSystem;25import org.apache.hadoop.hdfs.MiniDFSCluster;26import org.apache.hadoop.util.Daemon;27import org.mockito.invocation.InvocationOnMock;28import org.mockito.stubbing.Answer;29import java.io.IOException;30import static org.mockito.Matchers.anyObject;31import static org.mockito.Matchers.anyString;32import static org.mockito.Mockito.doAnswer;33import static org.mockito.Mockito.spy;34public class TestLeaseManager extends TestCase {35  public static final Log LOG = LogFactory.getLog(TestLeaseManager.class);36  /*37   * test case: two leases are added for a singler holder, should use38   * the internalReleaseOne method39   */40  public void testMultiPathLeaseRecovery()41    throws IOException, InterruptedException {42    Configuration conf = new Configuration();43    MiniDFSCluster cluster = new MiniDFSCluster(conf, 3, true, null);44    NameNode namenode = cluster.getNameNode();45    FSNamesystem spyNamesystem = spy(namenode.getNamesystem());46    LeaseManager leaseManager = new LeaseManager(spyNamesystem);47    48    spyNamesystem.leaseManager = leaseManager;49    spyNamesystem.lmthread.interrupt();50    51    String holder = "client-1";52    String path1 = "/file-1";53    String path2 = "/file-2";54    55    CalledAnswer internalReleaseCalled = new CalledAnswer();56    CalledAnswer internalReleaseOneCalled = new CalledAnswer();57    doAnswer(internalReleaseCalled)58        .when(spyNamesystem)59        .internalReleaseLease((LeaseManager.Lease) anyObject(), anyString());60    doAnswer(internalReleaseOneCalled)61        .when(spyNamesystem)62        .internalReleaseLeaseOne((LeaseManager.Lease) anyObject(), anyString());63    64    leaseManager.setLeasePeriod(1, 2);65    leaseManager.addLease(holder, path1);66    leaseManager.addLease(holder, path2);67    Thread.sleep(1000);68    synchronized (spyNamesystem) { // checkLeases is always called with FSN lock69      leaseManager.checkLeases();70    }71    72    assertTrue("internalReleaseOne not called", internalReleaseOneCalled.isCalled());73    assertFalse("internalRelease called", internalReleaseCalled.isCalled());74  }75  76  private static class CalledAnswer<T> implements Answer<T>{77    private volatile boolean called = false;78    @Override79    public T answer(InvocationOnMock invocationOnMock) throws Throwable {80      called = true;81      82      return (T)invocationOnMock.callRealMethod();83    }84    public boolean isCalled() {85      return called;86    }87  }88}...release
Using AI Code Generation
1import org.mockito.Spy;2import org.mockito.Mockito;3import org.mockito.invocation.InvocationOnMock;4import org.mockito.stubbing.Answer;5import java.util.LinkedList;6import java.util.List;7import static org.mockito.Mockito.*;8public class MockitoSpyExample {9   @Spy LinkedList<String> spyList = new LinkedList<String>();10   @Spy List<String> spy = new LinkedList<String>();11   @Spy List<String> spy2 = new LinkedList<String>();12   @Spy List<String> spy3 = new LinkedList<String>();13   public void testSpy() {14      doReturn("foo").when(spy).get(0);15      spy.add("one");16      spy.add("two");17      System.out.println(spy.get(0));18      System.out.println(spy.get(0));19      System.out.println(spy.size());20   }21   public void testSpy2() {22      doReturn("foo").when(spy2).get(0);23      spy2.add("one");24      spy2.add("two");25      System.out.println(spy2.get(0));26      System.out.println(spy2.get(0));27      System.out.println(spy2.size());28   }29   public void testSpy3() {30      doReturn("foo").when(spy3).get(0);31      spy3.add("one");32      spy3.add("two");33      System.out.println(spy3.get(0));34      System.out.println(spy3.get(0));35      System.out.println(spy3.size());36   }37   public static void main(String args[]) {38      MockitoSpyExample obj = new MockitoSpyExample();39      obj.testSpy();40      obj.testSpy2();41      obj.testSpy3();42   }43}44import java.utilrelease
Using AI Code Generation
1import org.mockito.Spy;2import org.mockito.Mockito;3import java.util.ArrayList;4public class 1 {5    public static void main(String[] args) {6        ArrayList<String> spy = Mockito.spy(new ArrayList<String>());7        spy.add("one");8        spy.add("two");9        Mockito.verify(spy).add("one");10        Mockito.verify(spy).add("two");11        Mockito.verifyNoMoreInteractions(spy);12    }13}release
Using AI Code Generation
1package org.mockito;2public class Mockito {3    public static <T> T spy(T toMock) {4        return null;5    }6    public static <T> T mock(Class<T> classToMock) {7        return null;8    }9}10package org.mockito;11public class Spy {12    public static <T> T spy(T toMock) {13        return null;14    }15    public static <T> T mock(Class<T> classToMock) {16        return null;17    }18}19package org.mockito;20public class Mockito {21    public static <T> T spy(T toMock) {22        return null;23    }24    public static <T> T mock(Class<T> classToMock) {25        return null;26    }27}28package org.mockito;29public class Spy {30    public static <T> T spy(T toMock) {31        return null;32    }33    public static <T> T mock(Class<T> classToMock) {34        return null;35    }36}37package org.mockito;38public class Mockito {39    public static <T> T spy(T toMock) {40        return null;41    }42    public static <T> T mock(Class<T> classToMock) {43        return null;44    }45}46package org.mockito;47public class Spy {48    public static <T> T spy(T toMock) {49        return null;50    }51    public static <T> T mock(Class<T> classToMock) {52        return null;53    }54}55package org.mockito;56public class Mockito {57    public static <T> T spy(T toMock) {58        return null;59    }60    public static <T> T mock(Class<T> classToMock) {61        return null;62    }63}64package org.mockito;65public class Spy {release
Using AI Code Generation
1import java.util.List;2import java.util.ArrayList;3import org.mockito.Mockito;4import org.mockito.Spy;5public class SpyRelease {6    public static void main(String[] args) {7        @Spy List<String> list = new ArrayList<String>();8        list.add("one");9        list.add("two");10        Mockito.verify(list).add("one");11        Mockito.verify(list).add("two");12        Mockito.release(list);13        Mockito.verifyNoMoreInteractions(list);14    }15}161. -> at SpyRelease.main(SpyRelease.java:17)17    verify(mock).someMethod();18    verify(mock, times(10)).someMethod();19    verify(mock, atLeastOnce()).someMethod();20    verify(mock, atLeast(10)).someMethod();21    verify(mock, atMost(10)).someMethod();22    verify(mock, never()).someMethod();23    verify(mock, timeout(100)).someMethod();24    verify(mock, timeout(100).times(5)).someMethod();25    verify(mock, timeout(100).atLeastOnce()).someMethod();26    verify(mock, timeout(100).atLeast(10)).someMethod();27    verify(mock, timeout(100).atMost(10)).someMethod();28    verify(mock, timeout(100).never()).someMethod();29    verify(mock, timeout(100).description("some description")).someMethod();30    verifyNoMoreInteractions(mock);31    verifyZeroInteractions(mock);32    verify(mock, never()).someMethod();33    verify(mock, never()).someMethod();34    verify(mock, times(0)).someMethod();35    verify(mock, times(0)).someMethod();36    verify(mock, atLeast(0)).someMethod();37    verify(mock, atLeast(0)).someMethod();38    verify(mock, atMost(0)).someMethod();39    verify(mock, atMost(0)).someMethod();40    verify(mock, never()).someMethod();41    verify(mock, never()).someMethod();42    verify(mock, times(0)).someMethod();43    verify(mock, times(0)).someMethod();44    verify(mock, atLeast(0)).someMethodrelease
Using AI Code Generation
1package org.mockito;2import org.junit.Test;3import static org.junit.Assert.*;4import static org.mockito.Mockito.*;5import java.util.*;6import java.util.concurrent.*;7public class MockitoSpyTest {8    public void testSpy() {9        List<String> list = new ArrayList<String>();10        List<String> spy = spy(list);11        spy.add("one");12        spy.add("two");13        verify(spy).add("one");14        verify(spy).add("two");15        assertEquals(2, spy.size());16        when(spy.size()).thenReturn(100);17        assertEquals(100, spy.size());18    }19}release
Using AI Code Generation
1import org.mockito.Spy;2import org.mockito.Mockito;3import org.mockito.MockitoAnnotations;4import org.mockito.Mock;5import org.mockito.InOrder;6public class 1 {7    @Spy public List list = new ArrayList();8    @Mock public List list2 = new ArrayList();9    public void test() {10        MockitoAnnotations.initMocks(this);11        list2.add("one");12        list2.add("two");13        list.add("three");14        list.add("four");15        list.add("five");16        InOrder inOrder = Mockito.inOrder(list, list2);17        inOrder.verify(list).add("three");18        inOrder.verify(list).add("four");19        inOrder.verify(list).add("five");20        inOrder.verify(list2).add("one");21        inOrder.verify(list2).add("two");22        Mockito.verifyNoMoreInteractions(list, list2);23    }24}251. -> at 1.test(1.java:26)26list2.add("one");27-> at 1.test(1.java:26)28list2.add("two");29-> at 1.test(1.java:26)30at org.mockito.exceptions.misusing.UnfinishedVerificationException.create(UnfinishedVerificationException.java:27)31at org.mockito.internal.verification.api.VerificationDataImpl.checkForUnfinishedVerification(VerificationDataImpl.java:59)32at org.mockito.internal.verification.api.VerificationDataImpl.checkForUnfinishedVerification(VerificationDataImpl.java:51)33at org.mockito.internal.verification.VerificationDataInOrderWrapper.checkForUnfinishedVerification(VerificationDataInOrderWrapper.java:39)34at org.mockito.internal.verification.InOrderWrapper.verify(InOrderWrapper.java:57)35at 1.test(1.java:25)361. -> at 1.test(1.java:26)37list2.add("one");38-> at 1.test(1.java:26)39list2.add("two");40-> at 1.test(1.java:26)41at org.mockito.exceptions.misusing.UnfinishedVerificationException.create(UnfinishedVerificationException.java:27)release
Using AI Code Generation
1package org.example;2import org.junit.Test;3import org.mockito.Spy;4import org.mockito.MockitoAnnotations;5import org.mockito.MockitoAnnotations.Mock;6import static org.mockito.Mockito.*;7public class ExampleTest {8    private Example example;9    public void testRelease() {10        MockitoAnnotations.initMocks(this);11        example.release();12        verify(example, times(1)).release();13    }14}15package org.example;16import org.junit.Test;17import org.mockito.Spy;18import org.mockito.MockitoAnnotations;19import org.mockito.MockitoAnnotations.Mock;20import static org.mockito.Mockito.*;21public class ExampleTest {22    private Example example;23    public void testRelease() {24        MockitoAnnotations.initMocks(this);25        example.release();26        verify(example, times(1)).release();27    }28}29package org.example;30import org.junit.Test;31import org.mockito.Spy;32import org.mockito.MockitoAnnotations;33import org.mockito.MockitoAnnotations.Mock;34import static org.mockito.Mockito.*;35public class ExampleTest {36    private Example example;37    public void testRelease() {38        MockitoAnnotations.initMocks(this);39        example.release();40        verify(example, times(1)).release();41    }42}43package org.example;44import org.junit.Test;45import org.mockito.Spy;46import org.mockito.MockitoAnnotations;47import org.mockito.MockitoAnnotations.Mock;48import static org.mockito.Mockito.*;49public class ExampleTest {50    private Example example;51    public void testRelease() {52        MockitoAnnotations.initMocks(this);53        example.release();54        verify(example, times(1)).release();55    }56}57package org.example;58import org.junit.Test;59import org.mockito.Spy;60import org.mockito.MockitoAnnotations;61import org.mockito.MockitoAnnotations.Mock;62import static org.mockito.Mockito.*;63public class ExampleTest {64    private Example example;65    public void testRelease() {66        MockitoAnnotations.initMocks(this);67        example.release();68        verify(example, times(1)).release();69    }70}release
Using AI Code Generation
1import org.mockito.Mock;2import org.mockito.Mockito;3import org.mockito.Spy;4import org.mockito.MockitoAnnotations;5import org.mockito.MockitoAnnotations.Mock;6public class 1 {7    private ArrayList arrayList = new ArrayList();8    public static void main(String[] args) {9        MockitoAnnotations.initMocks(this);10        Mockito.when(arrayList.size()).thenReturn(100);11        Mockito.release(arrayList);12        arrayList.add("one");13        arrayList.add("two");14        System.out.println(arrayList.size());15    }16}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!!
