Best Mockito code snippet using org.mockito.Mockito.clearInvocations
Source:MarkerTest.java
...14// limitations under the License.15//16import static org.junit.Assert.assertEquals;17import static org.mockito.Mockito.anyInt;18import static org.mockito.Mockito.clearInvocations;19import static org.mockito.Mockito.mock;20import static org.mockito.Mockito.never;21import static org.mockito.Mockito.verify;22import static org.mockito.Mockito.verifyNoMoreInteractions;23import static org.mockito.Mockito.verifyZeroInteractions;24import org.junit.Before;25import org.junit.Test;26import waveview.WaveformPresentationModel;27import waveview.wavedata.NetDataModel;28import waveview.wavedata.TransitionVector;29public class MarkerTest {30 private final WaveformPresentationModel model = new WaveformPresentationModel();31 private final WaveformPresentationModel.Listener listener =32 mock(WaveformPresentationModel.Listener.class);33 @Before34 public void setUpTest() {35 // The scale determines how close the user has to click to a marker to36 // select it.37 model.setHorizontalScale(0.1);38 model.addListener(listener);39 }40 @Test41 public void findMarkerEmpty() {42 assertEquals(0, model.findMarkerAtOrBeforeTime(1000));43 }44 // Ensure no crash when removing marker from empty set45 @Test46 public void removeMarkerEmpty() {47 model.removeMarkerAtTime(1000);48 verifyZeroInteractions(listener);49 }50 @Test51 public void insertMarker() {52 model.addMarker("marker0", 1000);53 verify(listener).markerChanged(1000);54 verifyNoMoreInteractions(listener);55 assertEquals(0, model.findMarkerAtOrBeforeTime(1000));56 }57 @Test58 public void removeMarkerNoMatchBefore() {59 model.addMarker("marker0", 1000);60 clearInvocations(listener);61 model.removeMarkerAtTime(925); // less than marker time62 verifyZeroInteractions(listener);63 assertEquals(1,64 model.getMarkerCount()); // Marker should still be present65 }66 @Test67 public void removeMarkerNoMatchAfter() {68 model.addMarker("marker0", 1000);69 clearInvocations(listener);70 model.removeMarkerAtTime(1075); // greater than marker time71 verifyZeroInteractions(listener);72 assertEquals(1,73 model.getMarkerCount()); // Marker should still be present74 }75 @Test76 public void removeMarkerBeforeSingle() {77 // Marker is both first and last, test edge cases around it78 model.addMarker("marker0", 1000);79 clearInvocations(listener);80 model.removeMarkerAtTime(990);81 verify(listener).markerChanged(1000);82 verifyNoMoreInteractions(listener);83 assertEquals(0, model.getMarkerCount());84 }85 @Test86 public void removeMarkerAfterSingle() {87 // Marker is both first and last, test edge cases around it88 model.addMarker("marker0", 1000);89 clearInvocations(listener);90 model.removeMarkerAtTime(1010);91 verify(listener).markerChanged(1000);92 verifyNoMoreInteractions(listener);93 assertEquals(0, model.getMarkerCount());94 }95 // Remove a marker when there are multiple markers in the list96 @Test97 public void removeMarkerMulti() {98 model.addMarker("marker2", 100);99 model.addMarker("marker3", 200);100 model.addMarker("marker4", 300);101 model.addMarker("marker5", 400);102 clearInvocations(listener);103 model.removeMarkerAtTime(199);104 verify(listener).markerChanged(200);105 verifyNoMoreInteractions(listener);106 // Ensure other markers were unaffected107 assertEquals(3, model.getMarkerCount());108 assertEquals(100, model.getTimestampForMarker(0));109 assertEquals(300, model.getTimestampForMarker(1));110 assertEquals(400, model.getTimestampForMarker(2));111 }112 @Test113 public void removeAllMarkers() {114 model.addMarker("marker2", 100);115 model.addMarker("marker3", 200);116 model.addMarker("marker4", 300);117 model.addMarker("marker5", 400);118 clearInvocations(listener);119 model.removeAllMarkers();120 verify(listener).markerChanged(-1);121 verifyNoMoreInteractions(listener);122 assertEquals(0, model.getMarkerCount());123 }124 // Regression test: when the timescale is 1ns, couldn't remove markers125 @Test126 public void removeMarkerHighZoom() {127 model.setHorizontalScale(0.037);128 model.addMarker("marker1", 14);129 clearInvocations(listener);130 model.removeMarkerAtTime(14);131 verify(listener).markerChanged(14);132 verifyNoMoreInteractions(listener);133 assertEquals(0, model.getMarkerCount());134 }135 @Test136 public void getDescriptionForMarker() {137 model.addMarker("foo", 1000);138 assertEquals("foo", model.getDescriptionForMarker(0));139 }140 // Go to next marker when we are before the first marker141 @Test142 public void nextMarkerBeforeFirst() {143 model.addMarker("marker2", 100);144 model.addMarker("marker3", 200);145 model.setCursorPosition(20);146 clearInvocations(listener);147 model.nextMarker(false);148 verify(listener).cursorChanged(20, 100);149 verifyNoMoreInteractions(listener);150 assertEquals(100, model.getCursorPosition());151 assertEquals(100, model.getSelectionStart());152 }153 // Go to the next marker when we are on the first marker154 @Test155 public void nextMarkerFirst() {156 model.addMarker("marker2", 100);157 model.addMarker("marker3", 200);158 model.setCursorPosition(100);159 clearInvocations(listener);160 model.nextMarker(false);161 verify(listener).cursorChanged(100, 200);162 verifyNoMoreInteractions(listener);163 assertEquals(200, model.getCursorPosition());164 assertEquals(200, model.getSelectionStart());165 }166 // There is no next marker, shouldn't do anything167 @Test168 public void nextMarkerAtLast() {169 model.addMarker("marker1", 100);170 model.addMarker("marker2", 200);171 model.setCursorPosition(200);172 clearInvocations(listener);173 model.nextMarker(false);174 verifyZeroInteractions(listener);175 assertEquals(200, model.getCursorPosition());176 }177 @Test178 public void prevMarkerAfterLast() {179 model.addMarker("marker2", 100);180 model.addMarker("marker3", 200);181 model.setCursorPosition(500);182 clearInvocations(listener);183 model.prevMarker(false);184 verify(listener).cursorChanged(500, 200);185 verifyNoMoreInteractions(listener);186 assertEquals(200, model.getCursorPosition());187 assertEquals(200, model.getSelectionStart());188 }189 @Test190 public void prevMarkerOnLast() {191 model.addMarker("marker2", 100);192 model.addMarker("marker3", 200);193 model.setCursorPosition(200);194 clearInvocations(listener);195 model.prevMarker(false);196 verify(listener).cursorChanged(200, 100);197 verifyNoMoreInteractions(listener);198 assertEquals(100, model.getCursorPosition());199 assertEquals(100, model.getSelectionStart());200 }201 // There is no previous marker, shouldn't do anything202 @Test203 public void prevMarkerAtFirst() {204 model.addMarker("marker1", 100);205 model.addMarker("marker2", 200);206 model.setCursorPosition(100);207 clearInvocations(listener);208 model.prevMarker(false);209 verifyZeroInteractions(listener);210 assertEquals(100, model.getCursorPosition());211 }212 // Extend the selection while navigating to next marker213 @Test214 public void nextMarkerExtendSelection() {215 model.addMarker("marker1", 100);216 model.addMarker("marker2", 200);217 model.setCursorPosition(50);218 clearInvocations(listener);219 model.nextMarker(true);220 verify(listener).cursorChanged(50, 100);221 verifyNoMoreInteractions(listener);222 assertEquals(100, model.getCursorPosition());223 assertEquals(50, model.getSelectionStart());224 }225 // Extend the selection while navigating to previous marker226 @Test227 public void prevMarkerExtendSelection() {228 model.addMarker("marker2", 100);229 model.addMarker("marker3", 200);230 model.setCursorPosition(150);231 clearInvocations(listener);232 model.prevMarker(true);233 verify(listener).cursorChanged(150, 100);234 verifyNoMoreInteractions(listener);235 assertEquals(100, model.getCursorPosition());236 assertEquals(150, model.getSelectionStart());237 }238 @Test239 public void jumpToMarker() {240 model.addMarker("marker", 100);241 model.setCursorPosition(50);242 clearInvocations(listener);243 model.jumpToMarker(0, false);244 verify(listener).cursorChanged(50, 100);245 verifyNoMoreInteractions(listener);246 assertEquals(100, model.getCursorPosition());247 assertEquals(100, model.getSelectionStart());248 }249 @Test250 public void jumpToMarkerExtendSelection() {251 model.addMarker("marker", 100);252 model.setCursorPosition(50);253 clearInvocations(listener);254 model.jumpToMarker(0, true);255 verify(listener).cursorChanged(50, 100);256 verifyNoMoreInteractions(listener);257 assertEquals(100, model.getCursorPosition());258 assertEquals(50, model.getSelectionStart());259 }260 @Test261 public void clearMarkers() {262 model.addMarker("marker0", 1000);263 model.addMarker("marker1", 1200);264 clearInvocations(listener);265 model.clear();266 verify(listener).markerChanged(-1);267 verifyNoMoreInteractions(listener);268 assertEquals(0, model.getMarkerCount());269 }270 // Ensure removeAllNets doesn't affect markers271 @Test272 public void removeAllNets() {273 NetDataModel net1 = new NetDataModel(274 "net1", "net1", TransitionVector.Builder.createBuilder(1).getTransitionVector());275 model.addNet(net1);276 model.addMarker("a_marker", 1000);277 clearInvocations(listener);278 model.removeAllNets();279 verify(listener, never()).markerChanged(anyInt());280 assertEquals(1, model.getMarkerCount());281 }282}...
Source:Mocks.java
...18import org.mockito.stubbing.Answer;19public final class Mocks {20 private static final List<WeakReference<Object>> MOCKS = Collections.synchronizedList(new ArrayList<>());21 private static final Predicate<WeakReference<?>> IS_REFERENCE_CLEARED = reference -> reference.get() == null;22 private static final Consumer<WeakReference<Object>> CLEAR_INVOCATIONS_ON_REFERENCED_MOCK = reference -> Mockito.clearInvocations(reference.get());23 private static final Predicate<WeakReference<Object>> CLEAR_INVOCATIONS_ON_REFERENCED_MOCK_IF_REFERNCE_NOT_CLEARED = reference -> {24 if(IS_REFERENCE_CLEARED.test(reference)) return true;25 CLEAR_INVOCATIONS_ON_REFERENCED_MOCK.accept(reference);26 return false;27 };28 static {29 // Use a single predicate so that clearing references and invocations is an atomic operation30 // Otherwise, we could (rarely) run into:31 // 1) Mock is added32 // 2) Garbage collected references are removed33 // 3) Mock is garbage collected34 // 4) Mock invocations are cleared -> throws NullPointerException35 Lib199Subsystem.registerPeriodic(() -> MOCKS.removeIf(CLEAR_INVOCATIONS_ON_REFERENCED_MOCK_IF_REFERNCE_NOT_CLEARED));36 }37 38 /**39 * Attempts to create an instance of a class in which some or all of the classes methods are replaced with a mocked implementation40 * @param T the class type which will be mocked41 * @param U the class type which will be used to provide method implementations42 * @param classToMock the class type which will be mocked43 * @param implClass the object to which to try to forward method calls44 * @param interfaces a list of interfaces which the mocked object should extend45 * @return an instance of <code>T</code> in which some or all of the classes methods are replaced with a mocked implementation from <code>U</code>46 * @see #createMock(java.lang.Class, java.lang.Object, java.lang.Class...) 47 */48 public static <T, U> T createMock(Class<T> classToMock, U implClass, Class<?>... interfaces) {49 return createMock(classToMock, implClass, true, interfaces);50 }51 52 /**53 * Attempts to create an instance of a class in which some or all of the classes methods are replaced with a mocked implementation54 * @param T the class type which will be mocked55 * @param U the class type which will be used to provide method implementations56 * @param classToMock the class type which will be mocked57 * @param implClass the object to which to try to forward method calls58 * @param forwardUnknownCalls whether methods which are not overriden will call their real methods59 * @param interfaces a list of interfaces which the mocked object should extend60 * @return an instance of <code>T</code> in which some or all of the classes methods are replaced with a mocked implementation from <code>U</code>61 * @see #createMock(java.lang.Class, java.lang.Object) 62 */63 public static <T, U> T createMock(Class<T> classToMock, U implClass, boolean forwardUnknownCalls, Class<?>... interfaces) {64 return createMock(classToMock, implClass, forwardUnknownCalls ? InvocationOnMock::callRealMethod : new ReturnsSmartNulls(), interfaces);65 }66 67 /**68 * Attempts to create an instance of a class in which some or all of the classes methods are replaced with a mocked implementation69 * @param T the class type which will be mocked70 * @param U the class type which will be used to provide method implementations71 * @param classToMock the class type which will be mocked72 * @param implClass the object to which to try to forward method calls73 * @param defaultAnswer The answer to use when no overriden implementation is found74 * @param interfaces a list of interfaces which the mocked object should extend75 * @return an instance of <code>T</code> in which some or all of the classes methods are replaced with a mocked implementation from <code>U</code>76 * @see #createMock(java.lang.Class, java.lang.Object) 77 */78 public static <T, U> T createMock(Class<T> classToMock, U implClass, Answer<Object> defaultAnswer, Class<?>... interfaces) {79 HashMap<Method, InvokableMethod> methods = new HashMap<>();80 for(Method m: listMethods(classToMock, interfaces)) {81 if(Modifier.isStatic(m.getModifiers()) || Modifier.isFinal(m.getModifiers())) {82 continue;83 }84 try {85 Method mImpl = implClass.getClass().getMethod(m.getName(), m.getParameterTypes());86 if(!m.getReturnType().isAssignableFrom(mImpl.getReturnType())) {87 System.err.println("Method Return Types Not the Same for Method: " + m.getName());88 }89 methods.put(m, mImpl::invoke);90 } catch(NoSuchMethodException e) {}91 }92 MockSettings settings;93 if(interfaces.length == 0) {94 settings = Mockito.withSettings();95 } else {96 settings = Mockito.withSettings().extraInterfaces(interfaces);97 }98 settings = settings.defaultAnswer(new MockAnswer<>(methods, implClass, defaultAnswer));99 T mock = mock(classToMock, settings);100 return mock;101 }102 103 public static Method[] listMethods(Class<?> base, Class<?>... interfaces) {104 ArrayList<Method> out = new ArrayList<>();105 out.addAll(Arrays.asList(base.getMethods()));106 out.addAll(Arrays.stream(interfaces).map(Class::getMethods).flatMap(Arrays::stream).collect(Collectors.toList()));107 return out.toArray(Method[]::new);108 }109 /**110 * A wrapper for the underlying Mockito method which automatically calls {@link Mockito#clearInvocations(Object...)} to prevent memory leaks111 * 112 * @see Mockito#mock(Class)113 */114 public static <T> T mock(Class<T> classToMock) {115 return reportMock(Mockito.mock(classToMock));116 }117 /**118 * A wrapper for the underlying Mockito method which automatically calls {@link Mockito#clearInvocations(Object...)} to prevent memory leaks119 * 120 * @see Mockito#mock(Class, String)121 */122 public static <T> T mock(Class<T> classToMock, String name) {123 return reportMock(Mockito.mock(classToMock, name));124 }125 /**126 * A wrapper for the underlying Mockito method which automatically calls {@link Mockito#clearInvocations(Object...)} to prevent memory leaks127 * 128 * @see Mockito#mock(Class, Answer)129 */130 public static <T> T mock(Class<T> classToMock, Answer<?> defaultAnswer) {131 return reportMock(Mockito.mock(classToMock, defaultAnswer));132 }133 /**134 * A wrapper for the underlying Mockito method which automatically calls {@link Mockito#clearInvocations(Object...)} to prevent memory leaks135 * 136 * @see Mockito#mock(Class, MockSettings)137 */138 public static <T> T mock(Class<T> classToMock, MockSettings mockSettings) {139 return reportMock(Mockito.mock(classToMock, mockSettings));140 }141 /**142 * Registers a Mockito mock and periodically calls {@link Mockito#clearInvocations(Object...)} on it to prevent memory leaks143 * 144 * @param <T> The type of the mock145 * @param t The mock146 * @return The mock147 */148 public static <T> T reportMock(T t) {149 // Wrap in a WeakReference to prevent memory leaks on objects with no more references150 if(Mockito.mockingDetails(t).isMock()) MOCKS.add(new WeakReference<Object>(t));151 return t;152 }153 private Mocks() {}154 private static final class MockAnswer<U> implements Answer<Object> {155 private final HashMap<Method, InvokableMethod> methods;156 private final U impl;...
Source:TrustedWebActivityOpenTimeRecorderTest.java
...3// found in the LICENSE file.4package org.chromium.chrome.browser.browserservices.ui.controller.trustedwebactivity;5import static org.mockito.ArgumentMatchers.any;6import static org.mockito.ArgumentMatchers.anyLong;7import static org.mockito.Mockito.clearInvocations;8import static org.mockito.Mockito.doNothing;9import static org.mockito.Mockito.never;10import static org.mockito.Mockito.verify;11import static org.mockito.Mockito.when;12import org.junit.Before;13import org.junit.Test;14import org.junit.runner.RunWith;15import org.mockito.ArgumentCaptor;16import org.mockito.Captor;17import org.mockito.Mock;18import org.mockito.MockitoAnnotations;19import org.robolectric.Robolectric;20import org.robolectric.annotation.Config;21import org.chromium.base.test.BaseRobolectricTestRunner;22import org.chromium.chrome.browser.ActivityTabProvider;23import org.chromium.chrome.browser.browserservices.TrustedWebActivityUmaRecorder;24import org.chromium.chrome.browser.browserservices.ui.controller.CurrentPageVerifier;25import org.chromium.chrome.browser.browserservices.ui.controller.CurrentPageVerifier.VerificationState;26import org.chromium.chrome.browser.browserservices.ui.controller.CurrentPageVerifier.VerificationStatus;27import org.chromium.chrome.browser.lifecycle.ActivityLifecycleDispatcher;28import java.util.concurrent.TimeUnit;29/**30 * Tests for {@link TrustedWebActivityOpenTimeRecorder}.31 */32@RunWith(BaseRobolectricTestRunner.class)33@Config(manifest = Config.NONE)34public class TrustedWebActivityOpenTimeRecorderTest {35 @Mock36 ActivityLifecycleDispatcher mLifecycleDispatcher;37 @Mock38 CurrentPageVerifier mCurrentPageVerifier;39 @Mock40 TrustedWebActivityUmaRecorder mUmaRecorder;41 @Mock42 ActivityTabProvider mTabProvider;43 @Captor44 ArgumentCaptor<Runnable> mVerificationObserverCaptor;45 private TrustedWebActivityOpenTimeRecorder mRecorder;46 @Before47 public void setUp() {48 MockitoAnnotations.initMocks(this);49 doNothing()50 .when(mCurrentPageVerifier)51 .addVerificationObserver(mVerificationObserverCaptor.capture());52 mRecorder = new TrustedWebActivityOpenTimeRecorder(53 mLifecycleDispatcher, mCurrentPageVerifier, mUmaRecorder, mTabProvider);54 }55 @Test56 public void recordsTwaOpened() {57 launchTwa();58 verify(mUmaRecorder).recordTwaOpened(any());59 }60 @Test61 public void doesntRecordTwaOpenedTwice() {62 launchTwa();63 leaveVerifiedOrigin();64 clearInvocations(mUmaRecorder);65 returnToVerifiedOrigin();66 verify(mUmaRecorder, never()).recordTwaOpened(any());67 }68 @Test69 public void recordsTwaOpenTime_OnFirstActivityPause() {70 launchTwa();71 advanceTime(3000);72 mRecorder.onPauseWithNative();73 verify(mUmaRecorder).recordTwaOpenTime(3000);74 }75 @Test76 public void recordsTwaOpenTime_OnSecondActivityPause() {77 launchTwa();78 advanceTime(3000);79 mRecorder.onPauseWithNative();80 advanceTime(2000);81 mRecorder.onResumeWithNative();82 advanceTime(4000);83 clearInvocations(mUmaRecorder);84 mRecorder.onPauseWithNative();85 verify(mUmaRecorder).recordTwaOpenTime(4000);86 }87 @Test88 public void recordsTimeInVerified_WhenLeftVerified() {89 launchTwa();90 advanceTime(2000);91 leaveVerifiedOrigin();92 verify(mUmaRecorder).recordTimeInVerifiedOrigin(2000);93 }94 @Test95 public void recordsTimeOutOfVerified_WhenReturnedToVerified() {96 launchTwa();97 advanceTime(2000);98 leaveVerifiedOrigin();99 advanceTime(3000);100 returnToVerifiedOrigin();101 verify(mUmaRecorder).recordTimeOutOfVerifiedOrigin(3000);102 }103 @Test104 public void recordsTimeInVerified_WhenLeftVerifiedAgain() {105 launchTwa();106 advanceTime(2000);107 leaveVerifiedOrigin();108 advanceTime(3000);109 returnToVerifiedOrigin();110 advanceTime(4000);111 clearInvocations(mUmaRecorder);112 leaveVerifiedOrigin();113 verify(mUmaRecorder).recordTimeInVerifiedOrigin(4000);114 }115 @Test116 public void recordsTimeOutOfVerified_WhenReturnedToVerifiedAgain() {117 launchTwa();118 advanceTime(2000);119 leaveVerifiedOrigin();120 advanceTime(3000);121 returnToVerifiedOrigin();122 advanceTime(4000);123 leaveVerifiedOrigin();124 advanceTime(5000);125 clearInvocations(mUmaRecorder);126 returnToVerifiedOrigin();127 verify(mUmaRecorder).recordTimeOutOfVerifiedOrigin(5000);128 }129 @Test130 public void recordsTimeInVerified_WhenPausedWhileInVerified() {131 launchTwa();132 advanceTime(2000);133 mRecorder.onPauseWithNative();134 verify(mUmaRecorder).recordTimeInVerifiedOrigin(2000);135 }136 @Test137 public void recordsTimeInVerified_AfterResumedInVerified_AndLeftVerified() {138 launchTwa();139 advanceTime(2000);140 mRecorder.onPauseWithNative();141 advanceTime(3000);142 mRecorder.onResumeWithNative();143 advanceTime(4000);144 clearInvocations(mUmaRecorder);145 leaveVerifiedOrigin();146 verify(mUmaRecorder).recordTimeInVerifiedOrigin(4000);147 }148 @Test149 public void recordsTimeOutOfVerified_WhenPausedWhileOutOfVerified() {150 launchTwa();151 advanceTime(2000);152 leaveVerifiedOrigin();153 advanceTime(3000);154 mRecorder.onPauseWithNative();155 verify(mUmaRecorder).recordTimeOutOfVerifiedOrigin(3000);156 }157 @Test158 public void doesntRecordAnyTime_WhenVerifiedForFirstTime() {...
Source:DataEnabledSettingsTest.java
...18import static org.junit.Assert.assertFalse;19import static org.junit.Assert.assertTrue;20import static org.mockito.Matchers.anyInt;21import static org.mockito.Matchers.anyString;22import static org.mockito.Mockito.clearInvocations;23import static org.mockito.Mockito.doAnswer;24import static org.mockito.Mockito.doReturn;25import static org.mockito.Mockito.verify;26import android.os.HandlerThread;27import android.telephony.data.ApnSetting;28import android.test.suitebuilder.annotation.SmallTest;29import com.android.internal.telephony.TelephonyTest;30import org.junit.After;31import org.junit.Before;32import org.junit.Test;33import org.mockito.ArgumentCaptor;34import java.util.Objects;35public class DataEnabledSettingsTest extends TelephonyTest {36 private DataEnabledSettings mDataEnabledSettingsUT;37 private DataEnabledSettingsTestHandler mDataEnabledSettingsTestHandler;38 private String mRules = "";39 private class DataEnabledSettingsTestHandler extends HandlerThread {40 private DataEnabledSettingsTestHandler(String name) {41 super(name);42 }43 @Override44 public void onLooperPrepared() {45 mDataEnabledSettingsUT = new DataEnabledSettings(mPhone);46 setReady(true);47 }48 }49 @Before50 public void setUp() throws Exception {51 super.setUp(getClass().getSimpleName());52 doReturn(mRules).when(mSubscriptionController).getDataEnabledOverrideRules(anyInt());53 doAnswer(invocation -> {54 String rules = (String) invocation.getArguments()[1];55 boolean changed = !Objects.equals(mRules, rules);56 mRules = rules;57 return changed;58 }).when(mSubscriptionController).setDataEnabledOverrideRules(anyInt(), anyString());59 mDataEnabledSettingsTestHandler = new DataEnabledSettingsTestHandler(60 getClass().getSimpleName());61 mDataEnabledSettingsTestHandler.start();62 waitUntilReady();63 }64 @After65 public void tearDown() throws Exception {66 super.tearDown();67 }68 @Test69 @SmallTest70 public void testSetDataAllowedInVoiceCall() throws Exception {71 mDataEnabledSettingsUT.setAllowDataDuringVoiceCall(true);72 ArgumentCaptor<String> stringCaptor = ArgumentCaptor.forClass(String.class);73 verify(mSubscriptionController).setDataEnabledOverrideRules(anyInt(),74 stringCaptor.capture());75 assertEquals("*=nonDefault&inVoiceCall&DefaultDataOn&dsdsEnabled", stringCaptor.getValue());76 clearInvocations(mSubscriptionController);77 mDataEnabledSettingsUT.setAllowDataDuringVoiceCall(false);78 verify(mSubscriptionController).setDataEnabledOverrideRules(anyInt(),79 stringCaptor.capture());80 assertEquals("", stringCaptor.getValue());81 }82 @Test83 @SmallTest84 public void testSetAlwaysAllowMmsData() throws Exception {85 mDataEnabledSettingsUT.setUserDataEnabled(false);86 assertTrue(mDataEnabledSettingsUT.setAlwaysAllowMmsData(true));87 ArgumentCaptor<String> stringCaptor = ArgumentCaptor.forClass(String.class);88 verify(mSubscriptionController).setDataEnabledOverrideRules(anyInt(),89 stringCaptor.capture());90 assertEquals("mms=unconditionally", stringCaptor.getValue());91 assertTrue(mDataEnabledSettingsUT.isDataEnabled(ApnSetting.TYPE_MMS));92 clearInvocations(mSubscriptionController);93 assertTrue(mDataEnabledSettingsUT.setAlwaysAllowMmsData(false));94 verify(mSubscriptionController).setDataEnabledOverrideRules(anyInt(),95 stringCaptor.capture());96 assertEquals("", stringCaptor.getValue());97 assertFalse(mDataEnabledSettingsUT.isDataEnabled(ApnSetting.TYPE_MMS));98 mDataEnabledSettingsUT.setUserDataEnabled(true);99 assertTrue(mDataEnabledSettingsUT.isDataEnabled(ApnSetting.TYPE_MMS));100 }101}...
Source:GoogleDriveClientTest.java
...13import static org.junit.jupiter.api.Assertions.assertTrue;14import static org.mockito.ArgumentMatchers.any;15import static org.mockito.ArgumentMatchers.anyString;16import static org.mockito.ArgumentMatchers.eq;17import static org.mockito.Mockito.clearInvocations;18import static org.mockito.Mockito.verify;19import static org.mockito.Mockito.verifyNoInteractions;20import static org.mockito.Mockito.when;21@ExtendWith(MockitoExtension.class)22class GoogleDriveClientTest {23 @Mock(answer = Answers.RETURNS_DEEP_STUBS)24 private Drive googleDriveService;25 @Test26 public void testUpload() throws IOException {27 // given28 File fileToUpload = new File("src/test/resources/testFileToUpload.txt");29 String googleDriveRootFolderId = "parentFolderId";30 GoogleDriveClient googleService = new GoogleDriveClient(googleDriveService, googleDriveRootFolderId);31 com.google.api.services.drive.model.File fileMetadata = new com.google.api.services.drive.model.File();32 fileMetadata.setName("testFileToUpload.txt");33 fileMetadata.setParents(Collections.singletonList("parentFolderId"));34 FileContent notionExportFileContent = new FileContent("application/zip", fileToUpload);35 when(googleDriveService.files().create(any(), any()).setFields(anyString()).execute()).thenReturn(null);36 clearInvocations(googleDriveService);37 // when38 boolean result = googleService.upload(fileToUpload);39 // then40 assertTrue(result);41 verify(googleDriveService).files();42 // eq(notionExportFileContent) does not work I assume because FileContent doesn't override the equals method?43 // com.google.api.client.http.FileContent@66908383 is not the same as com.google.api.client.http.FileContent@736ac09a44 // but eq() works for com.google.api.services.drive.model.File -> the toString {"name" = "testFileToUpload.txt", "parents" = [parentFolderId]}45 verify(googleDriveService.files()).create(eq(fileMetadata), any(FileContent.class));46 verify(googleDriveService.files().create(eq(fileMetadata), any(FileContent.class))).setFields("id, parents");47 verify(googleDriveService.files().create(eq(fileMetadata), any(FileContent.class)).setFields("id, parents")).execute();48 }49 @Test50 public void testUpload_IOException() throws IOException {51 // given52 File fileToUpload = new File("src/test/resources/testFileToUpload.txt");53 String googleDriveRootFolderId = "parentFolderId";54 GoogleDriveClient googleService = new GoogleDriveClient(googleDriveService, googleDriveRootFolderId);55 com.google.api.services.drive.model.File fileMetadata = new com.google.api.services.drive.model.File();56 fileMetadata.setName("testFileToUpload.txt");57 fileMetadata.setParents(Collections.singletonList("parentFolderId"));58 when(googleDriveService.files().create(any(), any())).thenThrow(IOException.class);59 clearInvocations(googleDriveService);60 // when61 boolean result = googleService.upload(fileToUpload);62 // then63 assertFalse(result);64 verify(googleDriveService).files();65 verify(googleDriveService.files()).create(eq(fileMetadata), any(FileContent.class));66 }67 @Test68 public void testUpload_invalidFile() {69 // given70 File fileToUpload = new File("thisFileDoesNotExist.txt");71 String googleDriveRootFolderId = "parentFolderId";72 GoogleDriveClient googleService = new GoogleDriveClient(googleDriveService, googleDriveRootFolderId);73 // when...
Source:MockBeforeClass.java
...35 36 @BeforeMethod37 public void setUpMocks() {38 initMocks(this);39 Mockito.clearInvocations(friendshipWS);40 Mockito.clearInvocations(infoWS);41 Mockito.clearInvocations(userAdminWS);42 Mockito.clearInvocations(userWs);43 }44 45 public <T> T verify(T mock, int status) {46 return verify(mock, status, 1);47 }48 49 public <T> T verify(T mock, int status, int times) {50 return Mockito.verify(mock, status > 199 && status < 300 ? Mockito.times(times) : Mockito.never());51 }52 53 public final String FAKE_ID = Integer.toString(Integer.MAX_VALUE);54 55 public final String DP_ALLOW_ADMIN = "dataProviderAllowAdmin";56 ...
Source:TokenHolderTest.java
...3// found in the LICENSE file.4package org.chromium.ui.util;5import static org.junit.Assert.assertFalse;6import static org.junit.Assert.assertTrue;7import static org.mockito.Mockito.clearInvocations;8import static org.mockito.Mockito.mock;9import static org.mockito.Mockito.never;10import static org.mockito.Mockito.verify;11import org.junit.Test;12import org.junit.runner.RunWith;13import org.junit.runners.JUnit4;14@RunWith(JUnit4.class)15public class TokenHolderTest {16 private final Runnable mCallback = mock(Runnable.class);17 private final TokenHolder mHolder = new TokenHolder(mCallback);18 @Test19 public void hasTokens_AfterAddingOne() {20 mHolder.acquireToken();21 assertTrue(mHolder.hasTokens());22 }23 @Test24 public void hasNoTokens_AfterRemovingTheToken() {25 int token = mHolder.acquireToken();26 mHolder.releaseToken(token);27 assertFalse(mHolder.hasTokens());28 }29 @Test30 public void hasNoTokens_AfterAddingAndRemovingTwoTokens() {31 int token1 = mHolder.acquireToken();32 int token2 = mHolder.acquireToken();33 mHolder.releaseToken(token1);34 mHolder.releaseToken(token2);35 assertFalse(mHolder.hasTokens());36 }37 @Test38 public void hasTokens_AfterTryingToRemoveInvalidToken() {39 int token1 = mHolder.acquireToken();40 mHolder.releaseToken(token1 + 1);41 assertTrue(mHolder.hasTokens());42 }43 @Test44 public void callbackIsCalled_whenTokensBecomeEmptyOrNotEmpty() {45 int token1 = mHolder.acquireToken();46 verify(mCallback).run();47 clearInvocations(mCallback);48 int token2 = mHolder.acquireToken();49 verify(mCallback, never()).run();50 clearInvocations(mCallback);51 mHolder.releaseToken(token2);52 verify(mCallback, never()).run();53 clearInvocations(mCallback);54 mHolder.releaseToken(token1);55 verify(mCallback).run();56 }57}...
Source:ResetInvocationsTest.java
...15 public void reset_invocations_should_reset_only_invocations() {16 when(methods.simpleMethod()).thenReturn("return");17 methods.simpleMethod();18 verify(methods).simpleMethod();19 clearInvocations(methods);20 verifyNoMoreInteractions(methods);21 assertEquals("return", methods.simpleMethod());22 }23 @Test24 public void should_reset_invocations_on_multiple_mocks() {25 methods.simpleMethod();26 moarMethods.simpleMethod();27 clearInvocations(methods, moarMethods);28 verifyNoMoreInteractions(methods, moarMethods);29 }30 @Test(expected = NotAMockException.class)31 public void resettingNonMockIsSafe() {32 clearInvocations("");33 }34 @Test(expected = NotAMockException.class)35 public void resettingNullIsSafe() {36 clearInvocations(new Object[]{null});37 }38}...
clearInvocations
Using AI Code Generation
1package org.kodejava.example.mockito;2import org.junit.Test;3import org.mockito.Mockito;4import java.util.List;5public class ClearInvocationsTest {6 public void testClearInvocations() {7 List list = Mockito.mock(List.class);8 list.add("one");9 list.add("two");10 list.add("three");11 Mockito.verify(list).add("one");12 Mockito.verify(list).add("two");13 Mockito.verify(list).add("three");14 Mockito.clearInvocations(list);15 Mockito.verifyNoMoreInteractions(list);16 }17}
clearInvocations
Using AI Code Generation
1package org.kodejava.example.mockito;2import org.junit.Test;3import org.mockito.Mockito;4import java.util.List;5public class ClearInvocationsTest {6 public void testClearInvocations() {7 List list = Mockito.mock(List.class);8 list.add("one");9 list.add("two");10 list.add("three");11 Mockito.verify(list, Mockito.times(3)).add(Mockito.anyString());12 Mockito.clearInvocations(list);13 Mockito.verify(list, Mockito.never()).add(Mockito.anyString());14 }15}
clearInvocations
Using AI Code Generation
1package org.kodejava.example.mockito;2import org.junit.Test;3import org.mockito.Mockito;4import java.util.List;5import static org.mockito.Mockito.*;6public class ClearInvocationsTest {7 public void testClearInvocations() {8 List list = mock(List.class);9 when(list.get(0)).thenReturn("Hello World");10 Object value = list.get(0);11 System.out.println("value = " + value);12 Mockito.clearInvocations(list);13 when(list.get(0)).thenReturn("Hello Mockito");14 value = list.get(0);15 System.out.println("value = " + value);16 }17}
clearInvocations
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.InOrder;3import org.mockito.invocation.InvocationOnMock;4import org.mockito.stubbing.Answer;5import org.mockito.verification.VerificationMode;6import org.mockito.verification.VerificationWithTimeout;7import org.mockito.verification.VerificationAfterDelay;8import java.util.LinkedList;9class A {10 public A() {}11 public void method1() {12 System.out.println("method1");13 }14 public void method2() {15 System.out.println("method2");16 }17 public void method3() {18 System.out.println("method3");19 }20 public void method4() {21 System.out.println("method4");22 }23}24public class 1 {25 public static void main(String[] args) {26 A a = Mockito.mock(A.class);27 a.method1();28 a.method2();29 a.method3();30 a.method4();31 InOrder inOrder = Mockito.inOrder(a);32 inOrder.verify(a).method1();33 inOrder.verify(a).method2();34 inOrder.verify(a).method3();35 inOrder.verify(a).method4();36 Mockito.clearInvocations(a);37 a.method1();38 a.method2();39 a.method3();40 a.method4();41 inOrder.verify(a).method1();42 inOrder.verify(a).method2();43 inOrder.verify(a).method3();44 inOrder.verify(a).method4();45 }46}
clearInvocations
Using AI Code Generation
1import org.mockito.Mockito;2public class 1 {3 public static void main(String[] args) {4 List list = Mockito.mock(List.class);5 list.add("one");6 list.clear();7 Mockito.verify(list).clear();8 Mockito.clearInvocations(list);9 Mockito.verify(list, Mockito.never()).clear();10 }11}12-> at 1.main(1.java:11)
clearInvocations
Using AI Code Generation
1import static org.mockito.Mockito.*;2import org.mockito.Mockito;3import org.mockito.InOrder;4public class 1 {5 public static void main(String[] args) {6 List mockedList = mock(List.class);7 mockedList.add("one");8 mockedList.clear();9 verify(mockedList).add("one");10 verify(mockedList).clear();11 Mockito.clearInvocations(mockedList);12 mockedList.add("two");13 mockedList.clear();14 verify(mockedList).add("two");15 verify(mockedList).clear();16 }17}18Following stubbings are unnecessary (click to navigate to relevant line of code):191. -> at 1.main(1.java:16)20 at org.mockito.exceptions.misusing.UnnecessaryStubbingException.create(UnnecessaryStubbingException.java:35)21 at org.mockito.internal.stubbing.StubbedInvocationMatcher.reportUnused(StubbedInvocationMatcher.java:100)22 at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:89)23 at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)24 at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38)25 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:62)26 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.intercept(MockMethodInterceptor.java:47)27 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptSuperCallable(MockMethodInterceptor.java:129)28 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptSuperCallable(MockMethodInterceptor.java:120)29 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.invoke(MockMethodInterceptor.java:114)30 at java.base/java.util.List.clear(List.java:683)31 at 1.main(1.java:16)32import static org.mockito.Mockito.*;33import org.mockito.Mockito;34import org.mockito.InOrder;35import java
clearInvocations
Using AI Code Generation
1import org.mockito.Mockito;2public class 1 {3 public static void main(String[] args) {4 List<String> mockedList = mock(List.class);5 mockedList.add("one");6 mockedList.clear();7 verify(mockedList).add("one");8 verify(mockedList).clear();9 Mockito.clearInvocations(mockedList);10 verify(mockedList, times(0)).add("one");11 verify(mockedList, times(0)).clear();12 }13}14-> at 1.main(1.java:15)15import org.mockito.Mockito;16public class 1 {17 public static void main(String[] args) {18 List<String> mockedList = mock(List.class);19 mockedList.add("one");20 mockedList.clear();21 verify(mockedList).add("one");22 verify(mockedList).clear();23 Mockito.clearInvocations(mockedList);24 verifyNoMoreInteractions(mockedList);25 }26}27-> at 1.main(1.java:15)
clearInvocations
Using AI Code Generation
1import org.mockito.Mockito;2import java.util.List;3import java.util.LinkedList;4public class MockitoClearInvocationsExample {5 public static void main(String args[]) {6 List mockedList = Mockito.mock(LinkedList.class);7 mockedList.add("one");8 mockedList.clear();9 Mockito.verify(mockedList).add("one");10 Mockito.verify(mockedList).clear();11 Mockito.clearInvocations(mockedList);12 Mockito.verify(mockedList, Mockito.never()).add("one");13 Mockito.verify(mockedList, Mockito.never()).clear();14 }15}16-> at MockitoClearInvocationsExample.main(MockitoClearInvocationsExample.java:19)17-> at MockitoClearInvocationsExample.main(MockitoClearInvocationsExample.java:16)18 Mockito.verify(mockedList).add("one");19 symbol: method add(String)20 Mockito.verify(mockedList).clear();21 symbol: method clear()22 Mockito.verify(mockedList, Mockito.never()).add("one");23 symbol: method add(String)24 Mockito.verify(mockedList, Mockito.never()).clear();25 symbol: method clear()
clearInvocations
Using AI Code Generation
1package com.ack.mockito;2import org.mockito.Mockito;3public class ClearInvocations {4 public static void main(String[] args) {5 Foo foo = Mockito.mock(Foo.class);6 foo.doSomething();7 Mockito.verify(foo).doSomething();8 Mockito.clearInvocations(foo);9 Mockito.verify(foo, Mockito.never()).doSomething();10 }11}12class Foo {13 public void doSomething() {14 }15}
clearInvocations
Using AI Code Generation
1import static org.mockito.Mockito.*;2import org.mockito.Mockito;3import org.mockito.InOrder;4public class 1 {5 public static void main(String[] args) {6 List mockedList = mock(List.class);7 mockedList.add("one");8 mockedList.clear();9 verify(mockedList).add("one");10 verify(mockedList).clear();11 Mockito.clearInvocations(mockedList);12 mockedList.add("two");13 mockedList.clear();14 verify(mockedList).add("two");15 verify(mockedList).clear();16 }17}18Following stubbings are unnecessary (click to navigate to relevant line of code):191. -> at 1.main(1.java:16)20 at org.mockito.exceptions.misusing.UnnecessaryStubbingException.create(UnnecessaryStubbingException.java:35)21 at org.mockito.internal.stubbing.StubbedInvocationMatcher.reportUnused(StubbedInvocationMatcher.java:100)22 at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:89)23 at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)24 at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38)25 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:62)26 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.intercept(MockMethodInterceptor.java:47)27 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptSuperCallable(MockMethodInterceptor.java:129)28 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptSuperCallable(MockMethodInterceptor.java:120)29 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.invoke(MockMethodInterceptor.java:114)30 at java.base/java.util.List.clear(List.java:683)31 at 1.main(1.java:16)32import static org.mockito.Mockito.*;33import org.mockito.Mockito;34import org.mockito.InOrder;35import java
clearInvocations
Using AI Code Generation
1package org.kodejava.example.mockito;2import org.junit.Test;3import org.mockito.Mockito;4import java.util.List;5import static org.mockito.Mockito.*;6public class ClearInvocationsTest {7 public void testClearInvocations() {8 List list = mock(List.class);9 when(list.get(0)).thenReturn("Hello World");10 Object value = list.get(0);11 System.out.println("value = " + value);12 Mockito.clearInvocations(list);13 when(list.get(0)).thenReturn("Hello Mockito");14 value = list.get(0);15 System.out.println("value = " + value);16 }17}
clearInvocations
Using AI Code Generation
1import static org.mockito.Mockito.*;2import org.mockito.Mockito;3import org.mockito.InOrder;4public class 1 {5 public static void main(String[] args) {6 List mockedList = mock(List.class);7 mockedList.add("one");8 mockedList.clear();9 verify(mockedList).add("one");10 verify(mockedList).clear();11 Mockito.clearInvocations(mockedList);12 mockedList.add("two");13 mockedList.clear();14 verify(mockedList).add("two");15 verify(mockedList).clear();16 }17}18Following stubbings are unnecessary (click to navigate to relevant line of code):191. -> at 1.main(1.java:16)20 at org.mockito.exceptions.misusing.UnnecessaryStubbingException.create(UnnecessaryStubbingException.java:35)21 at org.mockito.internal.stubbing.StubbedInvocationMatcher.reportUnused(StubbedInvocationMatcher.java:100)22 at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:89)23 at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)24 at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38)25 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:62)26 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.intercept(MockMethodInterceptor.java:47)27 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptSuperCallable(MockMethodInterceptor.java:129)28 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptSuperCallable(MockMethodInterceptor.java:120)29 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.invoke(MockMethodInterceptor.java:114)30 at java.base/java.util.List.clear(List.java:683)31 at 1.main(1.java:16)32import static org.mockito.Mockito.*;33import org.mockito.Mockito;34import org.mockito.InOrder;35import java
clearInvocations
Using AI Code Generation
1import org.mockito.Mockito;2public class 1 {3 public static void main(String[] args) {4 List<String> mockedList = mock(List.class);5 mockedList.add("one");6 mockedList.clear();7 verify(mockedList).add("one");8 verify(mockedList).clear();9 Mockito.clearInvocations(mockedList);10 verify(mockedList, times(0)).add("one");11 verify(mockedList, times(0)).clear();12 }13}14-> at 1.main(1.java:15)15import org.mockito.Mockito;16public class 1 {17 public static void main(String[] args) {18 List<String> mockedList = mock(List.class);19 mockedList.add("one");20 mockedList.clear();21 verify(mockedList).add("one");22 verify(mockedList).clear();23 Mockito.clearInvocations(mockedList);24 verifyNoMoreInteractions(mockedList);25 }26}27-> at 1.main(1.java:15)
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!!