How to use Spy class of org.mockito package

Best Mockito code snippet using org.mockito.Spy

Source:CalculatorMockTest.java Github

copy

Full Screen

...3import org.junit.Before;4import org.junit.Test;5import org.mockito.Mock;6import org.mockito.MockitoAnnotations;7import org.mockito.Spy;8import org.mockito.cglib.proxy.Proxy;9import java.util.ArrayList;10import java.util.List;11import static org.junit.Assert.assertEquals;12import static org.mockito.Matchers.anyString;13import static org.mockito.Mockito.atLeast;14import static org.mockito.Mockito.atMost;15import static org.mockito.Mockito.doCallRealMethod;16import static org.mockito.Mockito.doNothing;17import static org.mockito.Mockito.doReturn;18import static org.mockito.Mockito.mock;19import static org.mockito.Mockito.never;20import static org.mockito.Mockito.spy;21import static org.mockito.Mockito.timeout;22import static org.mockito.Mockito.times;23import static org.mockito.Mockito.verify;24import static org.mockito.Mockito.verifyNoMoreInteractions;25import static org.mockito.Mockito.verifyZeroInteractions;26import static org.mockito.Mockito.when;27/**28 * Created by Lin.Hou on 2017/9/22.29 */30public class CalculatorMockTest {31 //Mock和Spy的区别,一个是主动性,一个是被动性的,主动性是Mock,期望调用多少次,与实际调用相比较,Spy不确定调用多少次,只能记录调用次数,传入参数等32 @Mock33 List list;34 //监视器35 @Spy36 ArrayList spyList;37 @Mock38 Calculator calculator1;39 @Spy40 Calculator calculator2;41 //以下几个是测试用的42 @Spy43 SpyUnit spyUnit;44 @Spy45 SpyUnit2 spyUnit2;46 @Mock47 SpyUnit2 mockUnit2;48 @Spy49 ArrayList spyUnit2List;50 @Spy51 SpyUnit3 spyUnit3;52 @Spy53 Calculator spyCalculator1;54 @Spy55 Calculator spyCalculator2;56 @Before57 public void setUp() throws Exception {58 MockitoAnnotations.initMocks(this);59 }60 @After61 public void tearDown() throws Exception {62 }63 @Test64 public void correctMockforVerify() throws Exception{65 list.add("String1");66 list.add("String1");67 list.add("String2");68 list.add("String3");69 list.add("String4");70 list.add(anyString());71 //验证add方法被调用72 verify(list).add("String2");73 //除了anyString还有anyChar,anyInt,anyBoolean,anyList等等74 // verify(list).add(anyString());75 //time的作用就是将验证这个方法调用的次数76 verify(list,times(2)).add("String1");77 //verify(list,times(2)).add("String2");78 verify(list,never()).add("String10");//从来没有发生过79 verify(list,atLeast(1)).add("String1");//最少被调用一次,最少调用次数80 verify(list,atMost(2)).add("String1");//最多被调用2次,最多调用次数81 }82 @Test83 public void errorMockforVerify() throws Exception{84 list.add("String1");85 list.add("String1");86 list.add("String2");87 list.add("String3");88 list.add("String4");89 list.add(anyString());90 verify(list,times(2)).add("String2");91 verify(list,never()).add("String4");92 verify(list,atMost(2)).add("String3");//最多被调用2次,最多调用次数93 }94 @Test95 public void correctMockforAny() throws Exception{96 list.add(anyString());97 //除了anyString还有anyChar,anyInt,anyBoolean,anyList等等98 verify(list).add(anyString());99 }100 @Test101 public void correctMockforAny1() throws Exception{102 list.add("ssss");103 //除了anyString还有anyChar,anyInt,anyBoolean,anyList等等104 verify(list).add(anyString());105 }106 @Test107 public void correctMockforWhen() throws Exception{108 when(list.get(0)).thenReturn("String");109 System.out.println(list.get(0));110 assertEquals("String",list.get(0));111 }112 @Test113 public void correctMockforWhen1() throws Exception{114 //因为是用@Spy注解的,所以在get(0)的是一定会数组越界,所以想要返回某个值得时候请用correctMockforSpyReturn的例子115 when(spyList.get(0)).thenReturn("String");116 System.out.println(spyList.get(0));117 }118 @Test119 public void correctMockforSpyReturn() throws Exception{120 doReturn("String").when(spyList).get(0);121 System.out.println(spyList.get(0));122 }123 @Test124 public void correctMockforSpyDoCallRealMethod() throws Exception{125 doCallRealMethod().when(calculator1).soutadd(1,2);126 assertEquals("输出结果是:3",calculator2.soutadd(1,2));127 }128 @Test129 public void mocktest4() throws Exception{130 //doThrow(new RuntimeException()).when(list).clear():如果仅仅这个方法的话,调用这个函数就会报错131 //但是加入doNoting就会发现没有报错132 doNothing().doThrow(new RuntimeException()).when(list).clear();133 list.clear();134 }135 // @Ignore//测试jacoco的命令时专门注释的136 @Test137 public void mocktest5() throws Exception{138 List li=spy(List.class);139 doReturn("sss").when(li).clear();140 li.clear();141 }142 @Test143 public void correctMockforMockTimes() throws Exception{144 list.get(0);145 list.get(0);146 verify(list,times(2)).get(0);147 }148 @Test149 public void correctMockforMockTimeout() throws Exception{150 list.get(0);151 list.get(0);152 verify(list,timeout(1000)).get(0);153 }154 @Test155 public void correctMockforMockTimeoutAndTimes() throws Exception{156 list.get(0);157 list.get(0);158 verify(list,timeout(1000).times(2)).get(0);159 }160 //验证是否有调用,但是还没验证的方法161 @Test162 public void correctMockforMockVerifyNoMoreInteractions() throws Exception{163 list.add("one");164 list.add("two");165 verify(list).add("one");166 verify(list).add("two");167 verifyNoMoreInteractions(list);168 }169 @Test170 public void errorMockforMockVerifyNoMoreInteractions() throws Exception{171 list.add("one");172 list.add("two");173 verify(list).add("one");174 verifyNoMoreInteractions(list);175 }176 //与上述内容正好相反,验证所有mock对象所有方法都没有被调用,调用后必须被验证,否则就有问题177 @Test178 public void correctMockforMockVerifyZeroInteractions() throws Exception{179 verifyZeroInteractions(list);180 }181 @Test182 public void errorMockforMockVerifyZeroInteractions() throws Exception{183 list.add("one");184 verifyZeroInteractions(list);185 }186 @Test187 public void correctMockforMockVerifyZeroInteractions1() throws Exception{188 list.add("one");189 verify(list).add("one");190 verifyZeroInteractions(list);191 }192 @Test193 public void mockAndSpy() throws Exception{194 spyList.add(anyString());195 verify(spyList).add(anyString());196 }197 @Test198 public void comparisonMockAndSpy() throws Exception{199 System.out.println(list.get(0));200 }201 @Test202 public void comparisonMockAndSpy1() throws Exception{203 assertEquals(3,spyUnit.add(1,2));204 }205 @Test206 public void comparisonMockAndSpy2() throws Exception{207 mockUnit2.listadd(spyUnit2List);208 verify(spyUnit2List,times(5)).add("String");209 System.out.println("-------------------------");210 spyUnit2.listadd(spyUnit2List);211 verify(spyUnit2List,times(5)).add("String");212 System.out.println("---------------------");213 }214 @Test215 public void comparisonClassAndSpy3() throws Exception{216 spyUnit3.add();217 verify(spyUnit3).add();218 assertEquals(3,spyUnit3.adds(1,2));219 }220 @Test221 public void comparisonClassAndSpy4() throws Exception{222 //mock通过动态代理的方式生成对象,但是这个对象有不是真实的对象。223 System.out.println(spyCalculator1.getClass().getName());224 System.out.println(spyCalculator1.hashCode());225 System.out.println(spyCalculator2.hashCode());226 spyCalculator1.setA(1);227 assertEquals(1,spyCalculator2.getA());228 }229 @Test230 public void comparisonClassAndSpy5() throws Exception{231 assertEquals(1,spyCalculator1.getA());232 }233}...

Full Screen

Full Screen

Source:TestQuorumJournalManagerUnit.java Github

copy

Full Screen

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.qjournal.client;19import static org.junit.Assert.fail;20import static org.mockito.Matchers.anyLong;21import static org.mockito.Matchers.eq;22import java.io.IOException;23import java.net.URI;24import java.util.List;25import org.junit.Assert;26import org.apache.commons.logging.impl.Log4JLogger;27import org.apache.hadoop.conf.Configuration;28import org.apache.hadoop.hdfs.qjournal.client.AsyncLogger;29import org.apache.hadoop.hdfs.qjournal.client.QuorumException;30import org.apache.hadoop.hdfs.qjournal.client.QuorumJournalManager;31import org.apache.hadoop.hdfs.qjournal.protocol.QJournalProtocolProtos.GetJournalStateResponseProto;32import org.apache.hadoop.hdfs.qjournal.protocol.QJournalProtocolProtos.NewEpochResponseProto;33import org.apache.hadoop.hdfs.server.namenode.EditLogOutputStream;34import org.apache.hadoop.hdfs.server.namenode.NameNodeLayoutVersion;35import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo;36import org.apache.hadoop.test.GenericTestUtils;37import org.apache.log4j.Level;38import org.junit.Before;39import org.junit.Test;40import org.mockito.Mockito;41import org.mockito.stubbing.Stubber;42import com.google.common.collect.ImmutableList;43import com.google.common.util.concurrent.Futures;44import com.google.common.util.concurrent.ListenableFuture;45import com.google.common.util.concurrent.SettableFuture;46import static org.apache.hadoop.hdfs.qjournal.QJMTestUtil.writeOp;47/**48 * True unit tests for QuorumJournalManager49 */50public class TestQuorumJournalManagerUnit {51 static {52 ((Log4JLogger)QuorumJournalManager.LOG).getLogger().setLevel(Level.ALL);53 }54 private static final NamespaceInfo FAKE_NSINFO = new NamespaceInfo(55 12345, "mycluster", "my-bp", 0L);56 private final Configuration conf = new Configuration();57 private List<AsyncLogger> spyLoggers;58 private QuorumJournalManager qjm;59 60 @Before61 public void setup() throws Exception {62 spyLoggers = ImmutableList.of(63 mockLogger(),64 mockLogger(),65 mockLogger());66 qjm = new QuorumJournalManager(conf, new URI("qjournal://host/jid"), FAKE_NSINFO) {67 @Override68 protected List<AsyncLogger> createLoggers(AsyncLogger.Factory factory) {69 return spyLoggers;70 }71 };72 for (AsyncLogger logger : spyLoggers) {73 futureReturns(GetJournalStateResponseProto.newBuilder()74 .setLastPromisedEpoch(0)75 .setHttpPort(-1)76 .build())77 .when(logger).getJournalState();78 79 futureReturns(80 NewEpochResponseProto.newBuilder().build()81 ).when(logger).newEpoch(Mockito.anyLong());82 83 futureReturns(null).when(logger).format(Mockito.<NamespaceInfo>any());84 }85 86 qjm.recoverUnfinalizedSegments();87 }88 89 private AsyncLogger mockLogger() {90 return Mockito.mock(AsyncLogger.class);91 }92 93 static <V> Stubber futureReturns(V value) {94 ListenableFuture<V> ret = Futures.immediateFuture(value);95 return Mockito.doReturn(ret);96 }97 98 static Stubber futureThrows(Throwable t) {99 ListenableFuture<?> ret = Futures.immediateFailedFuture(t);100 return Mockito.doReturn(ret);101 }102 @Test103 public void testAllLoggersStartOk() throws Exception {104 futureReturns(null).when(spyLoggers.get(0)).startLogSegment(Mockito.anyLong(),105 Mockito.eq(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION));106 futureReturns(null).when(spyLoggers.get(1)).startLogSegment(Mockito.anyLong(),107 Mockito.eq(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION));108 futureReturns(null).when(spyLoggers.get(2)).startLogSegment(Mockito.anyLong(),109 Mockito.eq(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION));110 qjm.startLogSegment(1, NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION);111 }112 @Test113 public void testQuorumOfLoggersStartOk() throws Exception {114 futureReturns(null).when(spyLoggers.get(0)).startLogSegment(Mockito.anyLong(),115 Mockito.eq(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION));116 futureReturns(null).when(spyLoggers.get(1)).startLogSegment(Mockito.anyLong(),117 Mockito.eq(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION));118 futureThrows(new IOException("logger failed"))119 .when(spyLoggers.get(2)).startLogSegment(Mockito.anyLong(),120 Mockito.eq(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION));121 qjm.startLogSegment(1, NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION);122 }123 @Test124 public void testQuorumOfLoggersFail() throws Exception {125 futureReturns(null).when(spyLoggers.get(0)).startLogSegment(Mockito.anyLong(),126 Mockito.eq(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION));127 futureThrows(new IOException("logger failed"))128 .when(spyLoggers.get(1)).startLogSegment(Mockito.anyLong(),129 Mockito.eq(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION));130 futureThrows(new IOException("logger failed"))131 .when(spyLoggers.get(2)).startLogSegment(Mockito.anyLong(),132 Mockito.eq(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION));133 try {134 qjm.startLogSegment(1, NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION);135 fail("Did not throw when quorum failed");136 } catch (QuorumException qe) {137 GenericTestUtils.assertExceptionContains("logger failed", qe);138 }139 }140 141 @Test142 public void testQuorumOutputStreamReport() throws Exception {143 futureReturns(null).when(spyLoggers.get(0)).startLogSegment(Mockito.anyLong(),144 Mockito.eq(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION));145 futureReturns(null).when(spyLoggers.get(1)).startLogSegment(Mockito.anyLong(),146 Mockito.eq(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION));147 futureReturns(null).when(spyLoggers.get(2)).startLogSegment(Mockito.anyLong(),148 Mockito.eq(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION));149 QuorumOutputStream os = (QuorumOutputStream) qjm.startLogSegment(1,150 NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION);151 String report = os.generateReport();152 Assert.assertFalse("Report should be plain text", report.contains("<"));153 }154 @Test155 public void testWriteEdits() throws Exception {156 EditLogOutputStream stm = createLogSegment();157 writeOp(stm, 1);158 writeOp(stm, 2);159 160 stm.setReadyToFlush();161 writeOp(stm, 3);162 163 // The flush should log txn 1-2164 futureReturns(null).when(spyLoggers.get(0)).sendEdits(165 anyLong(), eq(1L), eq(2), Mockito.<byte[]>any());166 futureReturns(null).when(spyLoggers.get(1)).sendEdits(167 anyLong(), eq(1L), eq(2), Mockito.<byte[]>any());168 futureReturns(null).when(spyLoggers.get(2)).sendEdits(169 anyLong(), eq(1L), eq(2), Mockito.<byte[]>any());170 stm.flush();171 // Another flush should now log txn #3172 stm.setReadyToFlush();173 futureReturns(null).when(spyLoggers.get(0)).sendEdits(174 anyLong(), eq(3L), eq(1), Mockito.<byte[]>any());175 futureReturns(null).when(spyLoggers.get(1)).sendEdits(176 anyLong(), eq(3L), eq(1), Mockito.<byte[]>any());177 futureReturns(null).when(spyLoggers.get(2)).sendEdits(178 anyLong(), eq(3L), eq(1), Mockito.<byte[]>any());179 stm.flush();180 }181 182 @Test183 public void testWriteEditsOneSlow() throws Exception {184 EditLogOutputStream stm = createLogSegment();185 writeOp(stm, 1);186 stm.setReadyToFlush();187 188 // Make the first two logs respond immediately189 futureReturns(null).when(spyLoggers.get(0)).sendEdits(190 anyLong(), eq(1L), eq(1), Mockito.<byte[]>any());191 futureReturns(null).when(spyLoggers.get(1)).sendEdits(192 anyLong(), eq(1L), eq(1), Mockito.<byte[]>any());193 194 // And the third log not respond195 SettableFuture<Void> slowLog = SettableFuture.create();196 Mockito.doReturn(slowLog).when(spyLoggers.get(2)).sendEdits(197 anyLong(), eq(1L), eq(1), Mockito.<byte[]>any());198 stm.flush();199 200 Mockito.verify(spyLoggers.get(0)).setCommittedTxId(1L);201 }202 private EditLogOutputStream createLogSegment() throws IOException {203 futureReturns(null).when(spyLoggers.get(0)).startLogSegment(Mockito.anyLong(),204 Mockito.eq(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION));205 futureReturns(null).when(spyLoggers.get(1)).startLogSegment(Mockito.anyLong(),206 Mockito.eq(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION));207 futureReturns(null).when(spyLoggers.get(2)).startLogSegment(Mockito.anyLong(),208 Mockito.eq(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION));209 EditLogOutputStream stm = qjm.startLogSegment(1,210 NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION);211 return stm;212 }213}...

Full Screen

Full Screen

Source:AttentionManagerServiceTest.java Github

copy

Full Screen

...44 * Tests for {@link com.android.server.attention.AttentionManagerService}45 */46@SmallTest47public class AttentionManagerServiceTest {48 private AttentionManagerService mSpyAttentionManager;49 private UserState mSpyUserState;50 private final int mTimeout = 1000;51 @Mock private AttentionCallbackInternal mMockAttentionCallbackInternal;52 @Mock private AttentionHandler mMockHandler;53 @Mock private IAttentionCallback mMockIAttentionCallback;54 @Mock private IPowerManager mMockIPowerManager;55 @Mock Context mContext;56 @Before57 public void setUp() throws RemoteException {58 MockitoAnnotations.initMocks(this);59 // setup context mock60 doReturn(true).when(mContext).bindServiceAsUser(any(), any(), anyInt(), any());61 // setup power manager mock62 PowerManager mPowerManager;63 doReturn(true).when(mMockIPowerManager).isInteractive();64 mPowerManager = new PowerManager(mContext, mMockIPowerManager, null);65 Object mLock = new Object();66 // setup a spy on attention manager67 AttentionManagerService mAttentionManager = new AttentionManagerService(68 mContext,69 mPowerManager,70 mLock,71 mMockHandler);72 mSpyAttentionManager = Mockito.spy(mAttentionManager);73 // setup a spy on user state74 ComponentName componentName = new ComponentName("a", "b");75 mSpyAttentionManager.mComponentName = componentName;76 UserState mUserState = new UserState(0,77 mContext,78 mLock,79 mMockHandler,80 componentName);81 mUserState.mService = new MockIAttentionService();82 mSpyUserState = spy(mUserState);83 }84 @Test85 public void testCancelAttentionCheck_noCrashWhenNoUserStateLocked() {86 mSpyAttentionManager.cancelAttentionCheck(null);87 }88 @Test89 public void testCancelAttentionCheck_noCrashWhenCallbackMismatched() {90 mSpyUserState.mCurrentAttentionCheck =91 new AttentionCheck(mMockAttentionCallbackInternal, mMockIAttentionCallback);92 doReturn(mSpyUserState).when(mSpyAttentionManager).peekCurrentUserStateLocked();93 mSpyAttentionManager.cancelAttentionCheck(null);94 }95 @Test96 public void testCancelAttentionCheck_cancelCallbackWhenMatched() {97 mSpyUserState.mCurrentAttentionCheck =98 new AttentionCheck(mMockAttentionCallbackInternal, mMockIAttentionCallback);99 doReturn(mSpyUserState).when(mSpyAttentionManager).peekCurrentUserStateLocked();100 mSpyAttentionManager.cancelAttentionCheck(mMockAttentionCallbackInternal);101 verify(mSpyAttentionManager).cancel(any());102 }103 @Test104 public void testCheckAttention_returnFalseWhenPowerManagerNotInteract() throws RemoteException {105 doReturn(false).when(mMockIPowerManager).isInteractive();106 AttentionCallbackInternal callback = Mockito.mock(AttentionCallbackInternal.class);107 assertThat(mSpyAttentionManager.checkAttention(mTimeout, callback)).isFalse();108 }109 @Test110 public void testCheckAttention_callOnSuccess() throws RemoteException {111 doReturn(true).when(mSpyAttentionManager).isServiceEnabled();112 doReturn(true).when(mMockIPowerManager).isInteractive();113 doReturn(mSpyUserState).when(mSpyAttentionManager).getOrCreateCurrentUserStateLocked();114 doNothing().when(mSpyAttentionManager).freeIfInactiveLocked();115 AttentionCallbackInternal callback = Mockito.mock(AttentionCallbackInternal.class);116 mSpyAttentionManager.checkAttention(mTimeout, callback);117 verify(callback).onSuccess(anyInt(), anyLong());118 }119 @Test120 public void testOnSwitchUser_noCrashCurrentServiceIsNull() {121 final int userId = 10;122 mSpyAttentionManager.getOrCreateUserStateLocked(userId);123 mSpyAttentionManager.onSwitchUser(userId);124 }125 private class MockIAttentionService implements IAttentionService {126 public void checkAttention(IAttentionCallback callback) throws RemoteException {127 callback.onSuccess(0, 0);128 }129 public void cancelAttentionCheck(IAttentionCallback callback) {130 }131 public IBinder asBinder() {132 return null;133 }134 }135}...

Full Screen

Full Screen

Source:SpyingOnRealObjectsTest.java Github

copy

Full Screen

...16import java.util.List;17import static org.mockito.Matchers.*;18import static org.mockito.Mockito.*;19@SuppressWarnings("unchecked")20public class SpyingOnRealObjectsTest extends TestBase {21 List list = new LinkedList();22 List spy = Mockito.spy(list);23 @Test24 public void shouldVerify() {25 spy.add("one");26 spy.add("two");27 assertEquals("one", spy.get(0));28 assertEquals("two", spy.get(1));29 verify(spy).add("one");30 verify(spy).add("two");31 }32 @Test33 public void shouldBeAbleToMockObjectBecauseWhyNot() {34 spy(new Object());35 }36 @Test37 public void shouldStub() {38 spy.add("one");39 when(spy.get(0))40 .thenReturn("1")41 .thenReturn("1 again");42 assertEquals("1", spy.get(0));43 assertEquals("1 again", spy.get(0));44 assertEquals("one", spy.iterator().next());45 assertEquals(1, spy.size());46 }47 @Test48 public void shouldAllowOverridingStubs() {49 when(spy.contains(anyObject())).thenReturn(true);50 when(spy.contains("foo")).thenReturn(false);51 assertTrue(spy.contains("bar"));52 assertFalse(spy.contains("foo"));53 }54 @SuppressWarnings("deprecation")55 @Test56 public void shouldStubVoid() {57 stubVoid(spy)58 .toReturn()59 .toThrow(new RuntimeException())60 .on().clear();61 spy.add("one");62 spy.clear();63 try {64 spy.clear();65 fail();66 } catch (RuntimeException e) {67 }68 assertEquals(1, spy.size());69 }70 @Test71 public void shouldStubWithDoReturnAndVerify() {72 doReturn("foo")73 .doReturn("bar")74 .when(spy).get(0);75 assertEquals("foo", spy.get(0));76 assertEquals("bar", spy.get(0));77 verify(spy, times(2)).get(0);78 verifyNoMoreInteractions(spy);79 }80 @Test81 public void shouldVerifyInOrder() {82 spy.add("one");83 spy.add("two");84 InOrder inOrder = inOrder(spy);85 inOrder.verify(spy).add("one");86 inOrder.verify(spy).add("two");87 verifyNoMoreInteractions(spy);88 }89 @Test90 public void shouldVerifyInOrderAndFail() {91 spy.add("one");92 spy.add("two");93 InOrder inOrder = inOrder(spy);94 inOrder.verify(spy).add("two");95 try {96 inOrder.verify(spy).add("one");97 fail();98 } catch (VerificationInOrderFailure f) {99 }100 }101 @Test102 public void shouldVerifyNumberOfTimes() {103 spy.add("one");104 spy.add("one");105 verify(spy, times(2)).add("one");106 verifyNoMoreInteractions(spy);107 }108 @Test109 public void shouldVerifyNumberOfTimesAndFail() {110 spy.add("one");111 spy.add("one");112 try {113 verify(spy, times(3)).add("one");114 fail();115 } catch (TooLittleActualInvocations e) {116 }117 }118 @Test119 public void shouldVerifyNoMoreInteractionsAndFail() {120 spy.add("one");121 spy.add("two");122 verify(spy).add("one");123 try {124 verifyNoMoreInteractions(spy);125 fail();126 } catch (NoInteractionsWanted e) {127 }128 }129 @Test130 public void shouldToString() {131 spy.add("foo");132 assertEquals("[foo]", spy.toString());133 }134 interface Foo {135 String print();136 }137 @Test138 public void shouldAllowSpyingAnonymousClasses() {139 //when140 Foo spy = spy(new Foo() {141 public String print() {142 return "foo";143 }144 });145 //then146 assertEquals("foo", spy.print());147 }148 @Test149 public void shouldSayNiceMessageWhenSpyingOnPrivateClass() throws Exception {150 List real = Arrays.asList("first", "second");151 try {152 spy(real);153 fail();154 } catch (MockitoException e) {155 assertContains("Most likely it is a private class that is not visible by Mockito", e.getMessage());156 }157 }158}...

Full Screen

Full Screen

Source:ClientBeatCheckTaskTest.java Github

copy

Full Screen

...11import org.junit.runner.RunWith;12import org.mockito.InjectMocks;13import org.mockito.Mock;14import org.mockito.Mockito;15import org.mockito.Spy;16import org.mockito.runners.MockitoJUnitRunner;17import org.springframework.test.util.ReflectionTestUtils;18import java.util.ArrayList;19import java.util.HashMap;20import java.util.List;21import java.util.Map;22/**23 * @author caoyixiong24 */25@RunWith(MockitoJUnitRunner.Silent.class)26public class ClientBeatCheckTaskTest {27 @InjectMocks28 @Spy29 private ClientBeatCheckTask clientBeatCheckTask;30 @Mock31 private DistroMapper distroMapperSpy;32 @Mock33 private Service serviceSpy;34 @Mock35 private GlobalConfig globalConfig;36 @Mock37 private PushService pushService;38 @Before39 public void init() {40 ReflectionTestUtils.setField(clientBeatCheckTask, "service", serviceSpy);41 Mockito.doReturn(distroMapperSpy).when(clientBeatCheckTask).getDistroMapper();42 Mockito.doReturn(globalConfig).when(clientBeatCheckTask).getGlobalConfig();43 Mockito.doReturn(pushService).when(clientBeatCheckTask).getPushService();44 }45 @Test46 public void testHeartBeatNotTimeout() {47 List<Instance> instances = new ArrayList<>();48 Instance instance = new Instance();49 instance.setLastBeat(System.currentTimeMillis());50 instance.setMarked(false);51 instance.setHealthy(true);52 Map<String, String> metadata = new HashMap<>();53 metadata.put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, "1000000000");54 instance.setMetadata(metadata);55 instances.add(instance);56 Mockito.when(serviceSpy.allIPs(true)).thenReturn(instances);57 Mockito.doReturn("test").when(serviceSpy).getName();58 Mockito.doReturn(true).when(distroMapperSpy).responsible(Mockito.anyString());59 clientBeatCheckTask.run();60 Assert.assertTrue(instance.isHealthy());61 }62 @Test63 public void testHeartBeatTimeout() {64 List<Instance> instances = new ArrayList<>();65 Instance instance = new Instance();66 instance.setLastBeat(System.currentTimeMillis() - 1000);67 instance.setMarked(false);68 instance.setHealthy(true);69 Map<String, String> metadata = new HashMap<>();70 metadata.put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, "10");71 instance.setMetadata(metadata);72 instances.add(instance);73 Mockito.doReturn("test").when(serviceSpy).getName();74 Mockito.doReturn(true).when(distroMapperSpy).responsible(Mockito.anyString());75 Mockito.when(serviceSpy.allIPs(true)).thenReturn(instances);76 clientBeatCheckTask.run();77 Assert.assertFalse(instance.isHealthy());78 }79 @Test80 public void testIpDeleteTimeOut() {81 List<Instance> instances = new ArrayList<>();82 Instance instance = new Instance();83 instance.setLastBeat(System.currentTimeMillis());84 instance.setMarked(true);85 instance.setHealthy(true);86 Map<String, String> metadata = new HashMap<>();87 metadata.put(PreservedMetadataKeys.IP_DELETE_TIMEOUT, "10");88 instance.setMetadata(metadata);89 instances.add(instance);90 Mockito.doReturn(true).when(distroMapperSpy).responsible(null);91 Mockito.doReturn(true).when(globalConfig).isExpireInstance();92 Mockito.when(serviceSpy.allIPs(true)).thenReturn(instances);93 clientBeatCheckTask.run();94 }95 @Test96 public void testIpDeleteNotTimeOut() {97 List<Instance> instances = new ArrayList<>();98 Instance instance = new Instance();99 instance.setLastBeat(System.currentTimeMillis());100 instance.setMarked(true);101 instance.setHealthy(true);102 Map<String, String> metadata = new HashMap<>();103 metadata.put(PreservedMetadataKeys.IP_DELETE_TIMEOUT, "10000");104 instance.setMetadata(metadata);105 instances.add(instance);106 Mockito.doReturn(true).when(distroMapperSpy).responsible(null);107 Mockito.doReturn(true).when(globalConfig).isExpireInstance();108 Mockito.when(serviceSpy.allIPs(true)).thenReturn(instances);109 clientBeatCheckTask.run();110 }111}...

Full Screen

Full Screen

Source:CalculadoraMockTest.java Github

copy

Full Screen

...5import org.mockito.ArgumentCaptor;6import org.mockito.Mock;7import org.mockito.Mockito;8import org.mockito.MockitoAnnotations;9import org.mockito.Spy;10public class CalculadoraMockTest {11 @Mock12 private Calculadora calckMock;13 @Spy14 private Calculadora calcSpy;15 16// @Spy17 private EmailService email; 18 @Before19 public void setup() {20 MockitoAnnotations.initMocks(this);21 }22 @Test23 public void deveMostrarDiferencaEntrewMockSpy() {24 /**25 * Quando o Mock não sabe o que fazer ele retorna o valor padrão 0;26 */27 System.out.println(calckMock.somar(1, 2));28 /**29 * Quando gravo uma espectativa30 */31 Mockito.when(calckMock.somar(1, 2)).thenReturn(8);32 System.out.println("MOCK: " + calckMock.somar(1, 2));33 34 /**35 * Para que o Mock utilize o metodo real podemos fazer 36 * desse modo37 */38 Mockito.when(calckMock.somar(1, 2)).thenCallRealMethod();39 System.out.println("MOCK REAL: " + calckMock.somar(1, 2));40 /**41 * Comportamento do Spy42 */43 Mockito.when(calcSpy.somar(1, 2)).thenReturn(8);44 System.out.println("SPY: " + calcSpy.somar(1, 2));45 46 /**47 * Caso em que o spy não vai saber o que fazer48 */49 System.out.println("SPY: " + calcSpy.somar(5, 5)); 50 /**51 * O spy como não sabe o que fazer ele faz a execução REAL do método52 * por isso não se pode usa-lo em inteface, não se pode "espiar uma inteface"53 */54 System.out.println("Mock");55 calckMock.imprime();56 System.out.println("Spy");57 calcSpy.imprime();58 /**59 * O Padrão do Mock é NÃO executar o metodo.60 * O Padrão do Spy é executar o metodo61 */62 63 /**64 * Para mudar o padrão do Spy65 */66 Mockito.doNothing().when(calcSpy).imprime();67 System.out.println("No Spy");68 calcSpy.imprime();69 70 /**71 * Mudar o comportamento 72 */73 Mockito.doReturn(5).when(calcSpy).somar(1, 2); //retorne 5 quando somar 1 e 274 75 }76 @Test77 public void teste() {78 Calculadora calc = Mockito.mock(Calculadora.class);79 ArgumentCaptor<Integer> argCapt = ArgumentCaptor.forClass(Integer.class);80 Mockito.when(calc.somar(argCapt.capture(), argCapt.capture())).thenReturn(5);81 assertEquals(5, calc.somar(1, 10000));82// System.out.println(argCapt.getValue());83// System.out.println(argCapt.getAllValues());84 }85}...

Full Screen

Full Screen

Source:PowerMockitoSpyAnnotationEngine.java Github

copy

Full Screen

...15 */16package org.powermock.api.mockito.internal.configuration;17import org.mockito.Captor;18import org.mockito.Mock;19import org.mockito.Spy;20import org.mockito.exceptions.base.MockitoException;21import org.mockito.internal.configuration.SpyAnnotationEngine;22import org.powermock.api.mockito.PowerMockito;23import org.powermock.reflect.Whitebox;24import java.lang.reflect.Field;25/**26 * More or less a copy of the {@link SpyAnnotationEngine} but it uses27 * {@link PowerMockito#spy(Object)} instead.28 */29public class PowerMockitoSpyAnnotationEngine extends SpyAnnotationEngine {30 @SuppressWarnings("deprecation")31 @Override32 public void process(Class<?> context, Object testClass) {33 Field[] fields = context.getDeclaredFields();34 for (Field field : fields) {35 if (field.isAnnotationPresent(Spy.class)) {36 try {37 Whitebox.invokeMethod(this, Spy.class, field, new Class<?>[] { Mock.class,38 org.mockito.MockitoAnnotations.Mock.class, Captor.class });39 } catch (RuntimeException e) {40 throw e;41 } catch (Exception e1) {42 throw new RuntimeException(e1);43 }44 boolean wasAccessible = field.isAccessible();45 field.setAccessible(true);46 try {47 Object instance = field.get(testClass);48 if (instance == null) {49 throw new MockitoException("Cannot create a @Spy for '" + field.getName()50 + "' field because the *instance* is missing\n" + "Example of correct usage of @Spy:\n"51 + " @Spy List mock = new LinkedList();\n");52 }53 field.set(testClass, PowerMockito.spy(instance));54 } catch (IllegalAccessException e) {55 throw new MockitoException("Problems initiating spied field " + field.getName(), e);56 } finally {57 field.setAccessible(wasAccessible);58 }59 }60 }61 }62}...

Full Screen

Full Screen

Source:MockitoSpyTest.java Github

copy

Full Screen

1package org.baeldung.mockito;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.mockito.Mockito;5import org.mockito.Spy;6import org.mockito.runners.MockitoJUnitRunner;7import java.util.ArrayList;8import java.util.List;9import static org.junit.Assert.assertEquals;10@RunWith(MockitoJUnitRunner.class)11public class MockitoSpyTest {12 @Spy13 private List<String> aSpyList = new ArrayList<String>();14 @Test15 public void whenSpyingOnList_thenCorrect() {16 final List<String> list = new ArrayList<String>();17 final List<String> spyList = Mockito.spy(list);18 spyList.add("one");19 spyList.add("two");20 Mockito.verify(spyList).add("one");21 Mockito.verify(spyList).add("two");22 assertEquals(2, spyList.size());23 }24 @Test25 public void whenUsingTheSpyAnnotation_thenObjectIsSpied() {26 aSpyList.add("one");27 aSpyList.add("two");28 Mockito.verify(aSpyList).add("one");29 Mockito.verify(aSpyList).add("two");30 assertEquals(2, aSpyList.size());31 }32 @Test33 public void whenStubASpy_thenStubbed() {34 final List<String> list = new ArrayList<String>();35 final List<String> spyList = Mockito.spy(list);36 assertEquals(0, spyList.size());37 Mockito.doReturn(100).when(spyList).size();38 assertEquals(100, spyList.size());39 }40 @Test41 public void whenCreateMock_thenCreated() {42 final List<String> mockedList = Mockito.mock(ArrayList.class);43 mockedList.add("one");44 Mockito.verify(mockedList).add("one");45 assertEquals(0, mockedList.size());46 }47 @Test48 public void whenCreateSpy_thenCreate() {49 final List<String> spyList = Mockito.spy(new ArrayList<String>());50 spyList.add("one");51 Mockito.verify(spyList).add("one");52 assertEquals(1, spyList.size());53 }54}...

Full Screen

Full Screen

Spy

Using AI Code Generation

copy

Full Screen

1import static org.mockito.Mockito.spy;2import static org.mockito.Mockito.when;3import java.util.ArrayList;4import java.util.List;5public class SpyTest {6 public static void main(String[] args) {7 List<String> list = new ArrayList<String>();8 List<String> spy = spy(list);9 System.out.println("spy.size() = " + spy.size());10 spy.add("one");11 spy.add("two");12 System.out.println("spy.size() = " + spy.size());13 when(spy.size()).thenReturn(100);14 System.out.println("spy.size() = " + spy.size());15 }16}17spy.size() = 018spy.size() = 219spy.size() = 100

Full Screen

Full Screen

Spy

Using AI Code Generation

copy

Full Screen

1package com.ack.j2se.mockito;2import static org.mockito.Mockito.spy;3import static org.mockito.Mockito.verify;4import java.util.ArrayList;5import java.util.List;6public class SpyExample {7 public static void main( String[] args ) {8 List<String> list = new ArrayList<String>();9 List<String> spyList = spy( list );10 spyList.add( "one" );11 spyList.add( "two" );12 verify( spyList ).add( "one" );13 verify( spyList ).add( "two" );14 System.out.println( spyList.get( 0 ) );15 System.out.println( spyList.get( 1 ) );16 }17}18package com.ack.j2se.mockito;19import static org.mockito.Mockito.doReturn;20import static org.mockito.Mockito.spy;21import java.util.ArrayList;22import java.util.List;23public class SpyExample {24 public static void main( String[] args ) {25 List<String> list = new ArrayList<String>();26 List<String> spyList = spy( list );27 doReturn( "foo" ).when( spyList ).get( 0 );28 System.out.println( spyList.get( 0 ) );29 }30}31package com.ack.j2se.mockito;32import static org.mockito.Mockito.doThrow;33import static org.mockito.Mockito.spy;34import java.util.ArrayList;35import java.util.List;36public class SpyExample {37 public static void main( String[] args ) {38 List<String> list = new ArrayList<String>();39 List<String> spyList = spy( list );40 doThrow( new RuntimeException() ).when( spyList ).clear();41 spyList.clear();42 }43}44package com.ack.j2se.mockito;45import static org.mockito.Mockito.doNothing;46import static org.mockito.Mockito.spy;47import java.util.ArrayList;48import java.util.List;49public class SpyExample {50 public static void main( String[] args ) {51 List<String> list = new ArrayList<String>();52 List<String> spyList = spy( list );53 doNothing().when( spyList ).clear();54 spyList.clear();55 }56}

Full Screen

Full Screen

Spy

Using AI Code Generation

copy

Full Screen

1import org.mockito.Spy;2import java.util.ArrayList;3import java.util.List;4public class SpyDemo {5 public static void main(String[] args) {6 List<String> list = new ArrayList<>();7 list.add("one");8 list.add("two");9 System.out.println("List: " + list);10 List<String> spyList = Mockito.spy(list);11 System.out.println("First element: " + spyList.get(0));12 System.out.println("List size: " + spyList.size());13 spyList.add("three");14 System.out.println("List: " + spyList);15 System.out.println("Second element: " + spyList.get(1));16 Mockito.verify(spyList).add("three");17 }18}19import org.mockito.Spy;20import java.util.ArrayList;21import java.util.List;22public class SpyDemo {23 public static void main(String[] args) {24 List<String> list = new ArrayList<>();25 list.add("one");26 list.add("two");27 System.out.println("List: " + list);28 List<String> spyList = Mockito.spy(list);29 System.out.println("First element: " + spyList.get(0));30 System.out.println("List size: " + spyList.size());31 spyList.add("three");32 System.out.println("List: " + spyList);33 System.out.println("Second element: " + spyList.get(1));

Full Screen

Full Screen

Spy

Using AI Code Generation

copy

Full Screen

1package com.ack.j2se.mock;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.spy;4import static org.mockito.Mockito.verify;5import java.util.ArrayList;6import java.util.List;7public class SpyExample {8 public static void main( String[] args ) {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 System.out.println( spy.get( 0 ) );16 System.out.println( spy.get( 1 ) );17 when( spy.size() ).thenReturn( 100 );18 System.out.println( spy.size() );19 verify( spy ).add( "one" );20 verify( spy ).add( "two" );21 }22}23package com.ack.j2se.mock;24import static org.mockito.Mockito.mock;25import static org.mockito.Mockito.spy;26import static org.mockito.Mockito.verify;27import java.util.ArrayList;28import java.util.List;29public class SpyExample {30 public static void main( String[] args ) {31 List<String> list = new ArrayList<String>();32 List<String> spy = spy( list );33 spy.add( "one" );34 spy.add( "two" );35 verify( spy ).add( "one" );36 verify( spy ).add( "two" );37 System.out.println( spy.get( 0 ) );38 System.out.println( spy.get( 1 ) );39 when( spy.size() ).thenReturn( 100 );40 System.out.println( spy.size() );41 verify( spy ).add( "one" );42 verify( spy ).add( "two" );43 }44}45package com.ack.j2se.mock;46import static org.mockito.Mockito.mock;47import static

Full Screen

Full Screen

Spy

Using AI Code Generation

copy

Full Screen

1import static org.mockito.Mockito.*;2import org.mockito.*;3import org.mockito.invocation.*;4import org.mockito.stubbing.*;5import org.mockito.verification.*;6import org.mockito.internal.*;7import org.mockito.exceptions.*;8import org.mockito.listeners.*;9import org.mockito.configuration.*;10import org.mockito.internal.matchers.*;11import org.mockito.internal.progress.*;12import org.mockito.internal.stubbing.*;13import org.mockito.internal.verification.*;14import org.mockito.internal.util.*;15import org.mockito.internal.invocation.*;16import org.mockito.internal.debugging.*;17import org.mockito.internal.stubbing.answers.*;18import org.mockito.internal.creation.*;19import org.mockito.internal.creation.jmock.*;20import org.mockito.internal.creation.cglib.*;21import org.mockito.internal.creation.bytebuddy.*;22import org.mockito.internal.creation.instance.*;23import org.mockito.internal.creation.jmock.ClassImposterizer.*;24import org.mockito.internal.creation.jmock.ClassImposterizer.*;25import org.mockito.internal.creation.util.*;26import org.mockito.internal.util.reflection.*;27import org.mockito.exceptions.b

Full Screen

Full Screen

Spy

Using AI Code Generation

copy

Full Screen

1import org.mockito.Mockito;2import org.mockito.MockitoAnnotations;3import org.mockito.Spy;4import org.mockito.Mock;5import org.mockito.InjectMocks;6import org.mockito.Captor;7import org.mockito.ArgumentCaptor;8import org.mockito.stubbing.OngoingStubbing;9import org.mockito.stubbing.Answer;10import org.mockito.invocation.InvocationOnMock;11import org.mockito.stubbing.Stubber;12import org.mockito.stubbing.Answer;13import org.mockito.stubbing.Stubber;14import org.mockito.stubbing.VoidMethodStubber;15import org.mockito.stubbing.OngoingStubbing;16import org.mockito.stubbing.DefaultAnswer;17import org.mockito.stubbing.Answer;18import org.mockito.stubbing.Stubber;19import org.mockito.stubbing.VoidMethodStubber;20import org.mockito.stubbing.OngoingStubbing;21import org.mockito.stubbing.DefaultAnswer;22import org.mockito.stubbing.Answer;23import org.mockito.stubbing.Stubber;24import org.mockito.stubbing.VoidMethodStubber;25import org.mockito.stubbing.OngoingStubbing;26import org.mockito.stubbing.DefaultAnswer;27import org.mockito.stubbing.Answer;28import org.mockito.stubbing.Stubber;29import org.mockito.stubbing.VoidMethodStubber;30import org.mockito.stubbing.OngoingStubbing;31import org.mockito.stubbing.DefaultAnswer;32import org.mockito.stubbing.Answer;33import org.mockito.stubbing.Stubber;34import org.mockito.stubbing.VoidMethodStubber;35import org.mockito.stubbing.OngoingStubbing;36import org.mockito.stubbing.DefaultAnswer;37import org.mockito.stubbing.Answer;38import org.mockito.stubbing.Stubber;39import org.mockito.stubbing.VoidMethodStubber;40import org.mockito.stubbing.OngoingStubbing;41import org.mockito.stubbing.DefaultAnswer;42import org.mockito.stubbing.Answer;43import org.mockito.stubbing.Stubber;44import org.mockito.stubbing.VoidMethodStubber;45import org.mockito.stubbing.OngoingStubbing;46import org.mockito.stubbing.DefaultAnswer;47import org.mockito.stubbing.Answer;48import org.mockito.stubbing.Stubber;49import org.mockito.stubbing.VoidMethodStubber;50import org.mockito.stubbing.OngoingStubbing;51import org.mockito.stubbing.DefaultAnswer;52import org.mockito.stubbing.Answer;53import org.mockito.stubbing.Stubber;54import org.mockito.stubbing.VoidMethodStubber;55import org.mockito.stubbing.OngoingStubbing;56import org.mockito.stubbing.DefaultAnswer;57import org.mockito.stubbing.Answer;58import org.mockito.stubbing.Stubber;59import org.mockito.stubbing.VoidMethodStub

Full Screen

Full Screen

Spy

Using AI Code Generation

copy

Full Screen

1package com.automobile;2import org.mockito.Mockito;3import org.mockito.Spy;4import org.junit.Test;5import static org.mockito.Mockito.*;6import static org.junit.Assert.*;7import java.util.List;8public class SpyTest {9 @Spy List<String> list = new ArrayList<String>();10 public void testSpy() {11 Mockito.when(list.size()).thenReturn(100);12 assertEquals(100, list.size());13 list.add("one");14 list.add("two");15 verify(list).add("one");16 verify(list).add("two");17 assertEquals(100, list.size());18 }19}20OK (1 test)

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mockito automation tests on LambdaTest cloud grid

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

Most used methods in Spy

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful