How to use after method of org.mockito.Mockito class

Best Mockito code snippet using org.mockito.Mockito.after

Source:MAsyncTaskTest.java Github

copy

Full Screen

...46 public Object run(Object[] strings) {47 return tester.run(strings);48 }49 @Override50 public void afterBackground(Object o) {51 tester.afterBackground(o);52 }53 @Override54 public void after(Object s) {55 tester.after(s);56 }57 @Override58 public void error(Throwable error) {59 tester.error(error);60 }61 @Override62 public void error(Object[] objects, Throwable error) {63 tester.error(objects, error);64 }65 @Override66 public void cancelled(Object[] objects) {67 tester.cancelled(objects);68 }69 };70 }71 @Test72 public void shouldExecuteCallbackBefore() {73 // When74 asyncTask.execute(executor);75 // Then76 Mockito.verify(tester, Mockito.after(100).times(1))77 .before();78 }79 @Test80 public void shouldExecuteCallbackAfterSuccess() {81 // Given82 String givenResult = "result";83 Mockito.when(tester.run(any(String[].class)))84 .thenReturn(givenResult);85 // When86 asyncTask.execute(executor);87 // Then88 Mockito.verify(tester, Mockito.after(100).times(1)).after(givenResult);89 Mockito.verify(tester, Mockito.never()).error(any(Throwable.class));90 }91 @Test92 public void shouldExecuteErrorCallbackOnException() {93 // Given94 RuntimeException givenError = new RuntimeException("Error in background");95 Mockito.when(tester.run(any(String[].class)))96 .thenThrow(givenError);97 // When98 asyncTask.execute(executor);99 // Then100 Mockito.verify(tester, Mockito.after(100).times(1)).error(givenError);101 Mockito.verify(tester, Mockito.never()).after(Mockito.anyString());102 }103 @Test104 public void shouldExecuteErrorCallbackWithInputsOnException() {105 // Given106 String[] givenInputs = new String[]{"string1", "string2"};107 RuntimeException givenError = new RuntimeException("Error in background");108 Mockito.when(tester.run(any(String[].class)))109 .thenThrow(givenError);110 // When111 asyncTask.execute(executor, givenInputs);112 // Then113 Mockito.verify(tester, Mockito.after(100).times(1)).error(eq(givenInputs), eq(givenError));114 Mockito.verify(tester, Mockito.never()).after(Mockito.anyString());115 }116 @Test117 public void shouldMapInvalidPhoneToAppropriateException() {118 // Given119 ApiIOException givenError = new ApiIOException(ApiErrorCode.PHONE_INVALID, "");120 Mockito.when(tester.run(any(Object[].class)))121 .thenThrow(givenError);122 // When123 asyncTask.execute(executor);124 // Then125 Mockito.verify(tester, Mockito.after(100).times(1))126 .error(any(Object[].class), eqInvalidParamErrorWith(givenError));127 Mockito.verify(tester, Mockito.never()).after(Mockito.any());128 }129 @Test130 public void shouldMapInvalidCustomValueToAppropriateException() {131 // Given132 ApiIOException givenError = new ApiIOException(ApiErrorCode.REQUEST_FORMAT_INVALID, "");133 Mockito.when(tester.run(any(Object[].class)))134 .thenThrow(givenError);135 // When136 asyncTask.execute(executor);137 // Then138 Mockito.verify(tester, Mockito.after(100).times(1))139 .error(any(Object[].class), eqInvalidParamErrorWith(givenError));140 Mockito.verify(tester, Mockito.never()).after(Mockito.any());141 }142 @Test143 public void shouldMapInvalidEmailToAppropriateException() {144 // Given145 ApiIOException givenError = new ApiIOException(ApiErrorCode.EMAIL_INVALID, "");146 Mockito.when(tester.run(any(Object[].class)))147 .thenThrow(givenError);148 // When149 asyncTask.execute(executor);150 // Then151 Mockito.verify(tester, Mockito.after(100).times(1))152 .error(any(Object[].class), eqInvalidParamErrorWith(givenError));153 Mockito.verify(tester, Mockito.never()).after(Mockito.any());154 }155 @Test156 public void shouldMapInvalidBirthdateToAppropriateException() {157 // Given158 ApiIOException givenError = new ApiIOException(ApiErrorCode.REQUEST_FORMAT_INVALID, "");159 Mockito.when(tester.run(any(Object[].class)))160 .thenThrow(givenError);161 // When162 asyncTask.execute(executor);163 // Then164 Mockito.verify(tester, Mockito.after(100).times(1))165 .error(any(Object[].class), eqInvalidParamErrorWith(givenError));166 Mockito.verify(tester, Mockito.never()).after(Mockito.any());167 }168 @Test169 public void shouldMapErrorWithContentAndInvalidParameterToAppropriateException() {170 // Given171 String givenContent = "content";172 ApiIOException givenError = new ApiBackendExceptionWithContent(ApiErrorCode.PHONE_INVALID, "", givenContent);173 Mockito.when(tester.run(any(Object[].class)))174 .thenThrow(givenError);175 // When176 asyncTask.execute(executor);177 // Then178 Mockito.verify(tester, Mockito.after(100).times(1))179 .error(any(Object[].class), eqInvalidParamErrorWithContent(givenError, givenContent));180 Mockito.verify(tester, Mockito.never()).after(Mockito.any());181 }182 @Test183 public void shouldExecuteAfterInBackground() {184 // Given185 String givenResult = "result";186 Mockito.when(tester.run(any(String[].class)))187 .thenReturn(givenResult);188 // When189 asyncTask.execute(executor);190 // Then191 Mockito.verify(tester, Mockito.after(100).times(1)).afterBackground(givenResult);192 }193 @Test194 public void shouldBeAbleToCancelExecution() {195 // Given196 Mockito.when(tester.shouldCancel()).thenReturn(true);197 // When198 asyncTask.execute(executor);199 // Then200 Mockito.verify(tester, Mockito.after(100).times(1)).before();201 Mockito.verify(tester, Mockito.times(1)).shouldCancel();202 Mockito.verify(tester, Mockito.times(1)).cancelled(any(Object[].class));203 Mockito.verify(tester, Mockito.never()).run(any(Object[].class));204 Mockito.verify(tester, Mockito.never()).after(any(Object.class));205 Mockito.verify(tester, Mockito.never()).afterBackground(any(Object.class));206 Mockito.verify(tester, Mockito.never()).error(any(Throwable.class));207 Mockito.verify(tester, Mockito.never()).error(any(Object[].class), any(Throwable.class));208 }209 // region private methods210 @NonNull211 private Throwable eqInvalidParamErrorWith(final ApiIOException innerException) {212 return eqBackendError(BackendInvalidParameterException.class, innerException, null);213 }214 @NonNull215 private Throwable eqInvalidParamErrorWithContent(final ApiIOException innerException, final Object content) {216 return eqBackendError(BackendInvalidParameterExceptionWithContent.class, innerException, content);217 }218 @NonNull219 private Throwable eqErrorWithContent(final ApiIOException innerException, final Object content) {...

Full Screen

Full Screen

Source:MockitoSessionTest.java Github

copy

Full Screen

...102 @Mock IMethods mock;103 // session without initMocks is not currently supported104 MockitoSession mockito = Mockito.mockitoSession().startMocking();105 @After106 public void after() {107 mockito.finishMocking();108 }109 @Test110 public void some_test() {111 assertNull(mock); // initMocks() was not used when configuring session112 }113 }114 public static class SessionWithoutInitMocksConfigured {115 @Mock IMethods mock;116 MockitoSession mockito =117 Mockito.mockitoSession().strictness(Strictness.LENIENT).startMocking();118 @After119 public void after() {120 mockito.finishMocking();121 }122 @Test123 public void some_test() {124 assertNull(mock); // initMocks() was not used when configuring session125 }126 }127 public static class SessionWithoutStrictnessConfigured {128 @Mock IMethods mock;129 MockitoSession mockito = Mockito.mockitoSession().initMocks(this).startMocking();130 @After131 public void after() {132 mockito.finishMocking();133 }134 @Test135 public void some_test() {136 assertNotNull(mock);137 }138 }139 public static class SessionWithIncorrectMockitoUsage {140 @Mock IMethods mock;141 MockitoSession mockito = Mockito.mockitoSession().initMocks(this).startMocking();142 @After143 public void after() {144 mockito.finishMocking();145 }146 @SuppressWarnings({"MockitoUsage", "CheckReturnValue"})147 @Test148 public void unfinished_stubbing() {149 when(mock.simpleMethod());150 }151 }152 public static class SessionWithTestFailureAndIncorrectMockitoUsage {153 @Mock IMethods mock;154 MockitoSession mockito = Mockito.mockitoSession().initMocks(this).startMocking();155 @After156 public void after() {157 mockito.finishMocking();158 }159 @SuppressWarnings({"MockitoUsage", "CheckReturnValue"})160 @Test161 public void unfinished_stubbing_with_other_failure() {162 when(mock.simpleMethod());163 assertTrue(false);164 }165 }166 public static class SessionWithManuallyInitializedMock {167 @Mock IMethods mock;168 IMethods mock2 = Mockito.mock(IMethods.class, "manual mock");169 MockitoSession mockito = Mockito.mockitoSession().initMocks(this).startMocking();170 @After171 public void after() {172 mockito.finishMocking();173 }174 @Test175 public void manual_mock_preserves_its_settings() {176 assertEquals(177 "mock",178 mockingDetails(mock).getMockCreationSettings().getMockName().toString());179 assertEquals(180 "manual mock",181 mockingDetails(mock2).getMockCreationSettings().getMockName().toString());182 }183 }184 public static class SessionWithUpdatedStrictness {185 @Mock IMethods mock;186 MockitoSession mockito =187 Mockito.mockitoSession()188 .initMocks(this)189 .strictness(Strictness.STRICT_STUBS)190 .startMocking();191 @After192 public void after() {193 mockito.finishMocking();194 }195 @Test196 public void manual_mock_preserves_its_settings() {197 when(mock.simpleMethod(1)).thenReturn("foo");198 // when199 mockito.setStrictness(Strictness.LENIENT);200 // then no exception is thrown, even though the arg is different201 mock.simpleMethod(2);202 }203 }204 public static class SessionWithOverriddenFailure {205 @Mock IMethods mock;206 MockitoSession mockito = Mockito.mockitoSession().initMocks(this).startMocking();207 @After208 public void after() {209 mockito.finishMocking(new RuntimeException("Boo!"));210 }211 @SuppressWarnings({"MockitoUsage", "CheckReturnValue"})212 @Test213 public void invalid_mockito_usage() {214 verify(mock);215 }216 }217 public static class SessionWithInitMocksFailure {218 @InjectMocks private ConstructorFail sut;219 MockitoSession mockito;220 @Before221 public void before() {222 mockito = Mockito.mockitoSession().initMocks(this).startMocking();223 }224 @After225 public void after() {226 if (mockito != null) {227 // so that we reduce amount of exceptions for easier assertions228 // otherwise we would get an NPE here229 mockito.finishMocking();230 }231 }232 @Test233 public void test1() {234 // should fail the same way235 }236 @Test237 public void test2() {238 // should fail the same way239 }...

Full Screen

Full Screen

Source:MRetryableTaskTest.java Github

copy

Full Screen

...38 public String run(String[] strings) {39 return tester.run(strings);40 }41 @Override42 public void after(String s) {43 tester.after(s);44 }45 @Override46 public void afterBackground(String s) {47 tester.afterBackground(s);48 }49 @Override50 public void error(Throwable error) {51 tester.error(error);52 }53 @Override54 public void error(String[] strings, Throwable error) {55 tester.error(strings, error);56 }57 @Override58 public void cancelled(String[] strings) {59 tester.cancelled(strings);60 }61 };62 }63 @Test64 public void shouldExecuteRunMultipleTimesOrError() {65 // Given66 MRetryPolicy givenRetryPolicy = new MRetryPolicy.Builder()67 .withMaxRetries(3)68 .withBackoffMultiplier(0)69 .withRetryOn(Throwable.class)70 .build();71 Mockito.when(tester.run(any(String[].class)))72 .thenThrow(new RuntimeException("Error"));73 // When74 retryableTask75 .retryWith(givenRetryPolicy)76 .execute(executor);77 // Then78 Mockito.verify(tester, Mockito.after(100).times(givenRetryPolicy.getMaxRetries() + 1 /* first run */))79 .run(any(String[].class));80 }81 @Test82 public void shouldExecuteRunUntilThereAreExceptions() {83 // Given84 String givenResult = "someResult";85 MRetryPolicy givenRetryPolicy = new MRetryPolicy.Builder()86 .withMaxRetries(3)87 .withBackoffMultiplier(0)88 .withRetryOn(Throwable.class)89 .build();90 Mockito.when(tester.run(any(String[].class)))91 .thenThrow(new RuntimeException("Error"))92 .thenReturn(givenResult);93 // When94 retryableTask95 .retryWith(givenRetryPolicy)96 .execute(executor);97 // Then98 Mockito.verify(tester, Mockito.after(100).times( 1 /* first run */ + 1 /* retry */))99 .run(any(String[].class));100 Mockito.verify(tester, Mockito.never()).error(any(Throwable.class));101 Mockito.verify(tester, Mockito.never()).error(any(String[].class), any(Throwable.class));102 Mockito.verify(tester, Mockito.times(1)).before();103 Mockito.verify(tester, Mockito.times(1)).after(givenResult);104 }105 @Test106 public void shouldExecuteRunOnceOnSuccess() {107 // Given108 MRetryPolicy givenRetryPolicy = new MRetryPolicy.Builder()109 .withMaxRetries(3)110 .withBackoffMultiplier(0)111 .build();112 // When113 retryableTask114 .retryWith(givenRetryPolicy)115 .execute(executor);116 // Then117 Mockito.verify(tester, Mockito.after(100).times(1))118 .run(any(String[].class));119 }120 @Test121 public void shouldExecuteBeforeCallbackOnce() {122 // Given123 MRetryPolicy givenRetryPolicy = new MRetryPolicy.Builder()124 .withMaxRetries(3)125 .withBackoffMultiplier(0)126 .build();127 // When128 retryableTask129 .retryWith(givenRetryPolicy)130 .execute(executor);131 // Then132 Mockito.verify(tester, Mockito.after(100).times(1))133 .before();134 }135 @Test136 public void shouldExecuteAfterCallbackOnce() {137 // Given138 MRetryPolicy givenRetryPolicy = new MRetryPolicy.Builder()139 .withMaxRetries(3)140 .withBackoffMultiplier(0)141 .build();142 // When143 retryableTask144 .retryWith(givenRetryPolicy)145 .execute(executor);146 // Then147 Mockito.verify(tester, Mockito.after(100).times(1))148 .after(Mockito.anyString());149 }150 @Test151 public void shouldExecuteAfterBackgroundCallbackOnce() {152 // Given153 MRetryPolicy givenRetryPolicy = new MRetryPolicy.Builder()154 .withMaxRetries(3)155 .withBackoffMultiplier(0)156 .build();157 // When158 retryableTask159 .retryWith(givenRetryPolicy)160 .execute(executor);161 // Then162 Mockito.verify(tester, Mockito.after(100).times(1))163 .afterBackground(Mockito.anyString());164 }165 @Test166 public void shouldExecuteErrorOnce() {167 // Given168 MRetryPolicy givenRetryPolicy = new MRetryPolicy.Builder()169 .withMaxRetries(3)170 .withBackoffMultiplier(0)171 .build();172 String[] givenInputs = {"input1", "input2"};173 RuntimeException givenError = new RuntimeException("Run failed");174 Mockito.when(tester.run(any(String[].class)))175 .thenThrow(givenError);176 // When177 retryableTask178 .retryWith(givenRetryPolicy)179 .execute(executor, givenInputs);180 // Then181 Mockito.verify(tester, Mockito.after(100).times(1))182 .error(givenError);183 Mockito.verify(tester, Mockito.after(100).times(1))184 .error(eq(givenInputs), eq(givenError));185 }186 @Test187 public void shouldNotRetryOnUnknownError() {188 // Given189 class DoRetryException extends RuntimeException {}190 class DontRetryException extends RuntimeException {}191 MRetryPolicy givenRetryPolicy = new MRetryPolicy.Builder()192 .withMaxRetries(2)193 .withRetryOn(DoRetryException.class)194 .withBackoffMultiplier(0)195 .build();196 Mockito.when(tester.run(any(String[].class)))197 .thenThrow(new DontRetryException());198 // When199 retryableTask200 .retryWith(givenRetryPolicy)201 .execute(executor);202 // Then203 Mockito.verify(tester, Mockito.after(100).times(1)).run(any(String[].class));204 }205 @Test206 public void shouldBeAbleToCancelExecution() {207 // Given208 Mockito.when(tester.shouldCancel()).thenReturn(true);209 MRetryPolicy givenRetryPolicy = new MRetryPolicy.Builder()210 .withMaxRetries(3)211 .withBackoffMultiplier(0)212 .build();213 // When214 retryableTask215 .retryWith(givenRetryPolicy)216 .execute(executor);217 // Then218 Mockito.verify(tester, Mockito.after(100).times(1)).before();219 Mockito.verify(tester, Mockito.times(1)).shouldCancel();220 Mockito.verify(tester, Mockito.times(1)).cancelled(any(String[].class));221 Mockito.verify(tester, Mockito.never()).run(any(String[].class));222 Mockito.verify(tester, Mockito.never()).after(anyString());223 Mockito.verify(tester, Mockito.never()).error(any(Throwable.class));224 Mockito.verify(tester, Mockito.never()).error(any(String[].class), any(Throwable.class));225 }226}...

Full Screen

Full Screen

Source:StrictStubbingEndToEndTest.java Github

copy

Full Screen

...24import org.mockitousage.strictness.ProductionCode;25public class StrictStubbingEndToEndTest {26 JUnitCore junit = new JUnitCore();27 @After28 public void after() {29 new StateMaster().clearMockitoListeners();30 }31 @Test32 public void finish_mocking_exception_does_not_hide_the_exception_from_test() {33 Result result = junit.run(UnnecessaryStubbing.class);34 assertThat(result)35 // both exceptions are reported to JUnit:36 .fails("unnecessary_stubbing", IllegalStateException.class)37 .fails("unnecessary_stubbing", UnnecessaryStubbingException.class);38 }39 @Test40 public void does_not_report_unused_stubbing_if_mismatch_reported() {41 Result result = junit.run(ReportMismatchButNotUnusedStubbing.class);42 assertThat(result).fails(1, PotentialStubbingProblem.class);43 }44 @Test45 public void strict_stubbing_does_not_leak_to_other_tests() {46 Result result =47 junit.run(48 LenientStrictness1.class,49 StrictStubsPassing.class,50 LenientStrictness2.class);51 // all tests pass, lenient test cases contain incorrect stubbing52 assertThat(result).succeeds(5);53 }54 @Test55 public void detects_unfinished_session() {56 Result result = junit.run(UnfinishedMocking.class);57 assertThat(result)58 .fails(59 UnfinishedMockingSessionException.class,60 "\n"61 + "Unfinished mocking session detected.\n"62 + "Previous MockitoSession was not concluded with 'finishMocking()'.\n"63 + "For examples of correct usage see javadoc for MockitoSession class.");64 }65 @Test66 public void concurrent_sessions_in_different_threads() throws Exception {67 final Map<Class, Result> results = new ConcurrentHashMap<Class, Result>();68 concurrently(69 new Runnable() {70 public void run() {71 results.put(StrictStubsPassing.class, junit.run(StrictStubsPassing.class));72 }73 },74 new Runnable() {75 public void run() {76 results.put(77 ReportMismatchButNotUnusedStubbing.class,78 junit.run(ReportMismatchButNotUnusedStubbing.class));79 }80 });81 assertThat(results.get(StrictStubsPassing.class)).succeeds(1);82 assertThat(results.get(ReportMismatchButNotUnusedStubbing.class)).fails(1);83 }84 public static class UnnecessaryStubbing {85 @Mock IMethods mock;86 MockitoSession mockito =87 Mockito.mockitoSession()88 .initMocks(this)89 .strictness(Strictness.STRICT_STUBS)90 .startMocking();91 @After92 public void after() {93 mockito.finishMocking();94 }95 @Test96 public void unnecessary_stubbing() {97 given(mock.simpleMethod("1")).willReturn("one");98 throw new IllegalStateException();99 }100 }101 public static class ReportMismatchButNotUnusedStubbing {102 @Mock IMethods mock;103 MockitoSession mockito =104 Mockito.mockitoSession()105 .initMocks(this)106 .strictness(Strictness.STRICT_STUBS)107 .startMocking();108 @After109 public void after() {110 mockito.finishMocking();111 }112 @Test113 public void mismatch() {114 given(mock.simpleMethod(1)).willReturn("");115 ProductionCode.simpleMethod(mock, 2);116 }117 }118 public static class StrictStubsPassing {119 @Mock IMethods mock;120 MockitoSession mockito =121 Mockito.mockitoSession()122 .initMocks(this)123 .strictness(Strictness.STRICT_STUBS)124 .startMocking();125 @After126 public void after() {127 mockito.finishMocking();128 }129 @Test130 public void used() {131 given(mock.simpleMethod(1)).willReturn("");132 mock.simpleMethod(1);133 }134 }135 public static class LenientStrictness1 {136 @Mock IMethods mock = Mockito.mock(IMethods.class);137 @Test138 public void unused() {139 given(mock.simpleMethod(1)).willReturn("");140 }...

Full Screen

Full Screen

Source:ClearDataDialogResultRecorderTest.java Github

copy

Full Screen

1// Copyright 2018 The Chromium Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4package org.chromium.chrome.browser.browserservices;5import static org.mockito.AdditionalAnswers.answerVoid;6import static org.mockito.ArgumentMatchers.any;7import static org.mockito.ArgumentMatchers.anyBoolean;8import static org.mockito.Mockito.clearInvocations;9import static org.mockito.Mockito.doAnswer;10import static org.mockito.Mockito.doNothing;11import static org.mockito.Mockito.never;12import static org.mockito.Mockito.times;13import static org.mockito.Mockito.verify;14import static org.mockito.Mockito.when;15import org.junit.Before;16import org.junit.Test;17import org.junit.runner.RunWith;18import org.mockito.ArgumentCaptor;19import org.mockito.Captor;20import org.mockito.Mock;21import org.mockito.MockitoAnnotations;22import org.robolectric.annotation.Config;23import org.chromium.base.test.BaseRobolectricTestRunner;24import org.chromium.chrome.browser.init.ChromeBrowserInitializer;25import org.chromium.chrome.browser.preferences.SharedPreferencesManager;26/**27 * Tests for {@link ClearDataDialogResultRecorder}.28 */29@RunWith(BaseRobolectricTestRunner.class)30@Config(manifest = Config.NONE)31public class ClearDataDialogResultRecorderTest {32 private final SharedPreferencesManager mPrefsManager = SharedPreferencesManager.getInstance();33 @Mock ChromeBrowserInitializer mBrowserInitializer;34 @Mock TrustedWebActivityUmaRecorder mUmaRecorder;35 @Captor ArgumentCaptor<Runnable> mTaskOnNativeInitCaptor;36 private ClearDataDialogResultRecorder mRecorder;37 @Before38 public void setUp() {39 MockitoAnnotations.initMocks(this);40 restartApp();41 }42 @Test43 public void records_WhenAccepted_AfterNativeInit() {44 mRecorder.handleDialogResult(true, true);45 finishNativeInit();46 verify(mUmaRecorder).recordClearDataDialogAction(true, true);47 }48 @Test49 public void records_WhenAccepted_IfNativeAlreadyInited() {50 finishNativeInit();51 mRecorder.handleDialogResult(true, true);52 verify(mUmaRecorder).recordClearDataDialogAction(true, true);53 }54 @Test55 public void records_WhenDismissed_IfNativeAlreadyInited() {56 finishNativeInit();57 mRecorder.handleDialogResult(false, true);58 verify(mUmaRecorder).recordClearDataDialogAction(false, true);59 }60 @Test61 public void defersRecording_WhenDismissed_IfNativeNotAlreadyInited() {62 mRecorder.handleDialogResult(false, true);63 verify(mUmaRecorder, never()).recordClearDataDialogAction(anyBoolean(), anyBoolean());64 }65 @Test66 public void makesDeferredRecordingOfDismissals() {67 mRecorder.handleDialogResult(false, true);68 restartApp();69 mRecorder.handleDialogResult(false, true);70 restartApp();71 mRecorder.handleDialogResult(false, false);72 restartApp();73 mRecorder.makeDeferredRecordings();74 verify(mUmaRecorder, times(2)).recordClearDataDialogAction(false, true);75 verify(mUmaRecorder).recordClearDataDialogAction(false, false);76 }77 @Test78 public void doesntMakeDeferredRecordingTwice() {79 mRecorder.handleDialogResult(false, true);80 restartApp();81 mRecorder.makeDeferredRecordings();82 restartApp();83 clearInvocations(mUmaRecorder);84 mRecorder.makeDeferredRecordings();85 verify(mUmaRecorder, never()).recordClearDataDialogAction(anyBoolean(), anyBoolean());86 }87 private void restartApp() {88 when(mBrowserInitializer.isFullBrowserInitialized()).thenReturn(false);89 doNothing()90 .when(mBrowserInitializer)91 .runNowOrAfterFullBrowserStarted(mTaskOnNativeInitCaptor.capture());92 mRecorder = new ClearDataDialogResultRecorder(() -> mPrefsManager, mBrowserInitializer,93 mUmaRecorder);94 }95 private void finishNativeInit() {96 for (Runnable task : mTaskOnNativeInitCaptor.getAllValues()) {97 task.run();98 }99 when(mBrowserInitializer.isFullBrowserInitialized()).thenReturn(true);100 doAnswer(answerVoid(Runnable::run))101 .when(mBrowserInitializer)102 .runNowOrAfterFullBrowserStarted(any());103 }104}...

Full Screen

Full Screen

Source:WifiScannerTest.java Github

copy

Full Screen

...64 mWifiScanner = new WifiScanner(mContext, mService, mLooper.getLooper());65 mLooper.dispatchAll();66 }67 /**68 * Clean up after tests.69 */70 @After71 public void cleanup() {72 validateMockitoUsage();73 }74 private void verifySetHotlistMessage(Handler handler) {75 ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);76 verify(handler, atLeastOnce()).handleMessage(messageCaptor.capture());77 assertEquals("message.what is not CMD_SET_HOTLIST",78 WifiScanner.CMD_SET_HOTLIST,79 messageCaptor.getValue().what);80 }81 /**82 * Test duplicate listeners for bssid tracking....

Full Screen

Full Screen

Source:MockitoTestNGListener.java Github

copy

Full Screen

...14 * method</em> (&#064;BeforeMethod, &#064;BeforeClass, etc) or a <em>test</em> method, i.e. mocks are initialized15 * once only once for each test instance.16 * </li>17 * <li>18 * As mocks are initialized only once, they will be reset after each <em>test method</em>.19 * See javadoc {@link org.mockito.Mockito#reset(Object[])}20 * </li>21 * <li>22 * Validates framework usage after each test method. See javadoc for {@link org.mockito.Mockito#validateMockitoUsage()}.23 * </li>24 * </ul>25 *26 * <p>27 * The listener is completely optional - there are other ways you can get &#064;Mock working, for example by writing a base class.28 * Explicitly validating framework usage is also optional because it is triggered automatically by Mockito every time you use the framework.29 * See javadoc for {@link org.mockito.Mockito#validateMockitoUsage()}.30 *31 * <p>32 * Read more about &#064;Mock annotation in javadoc for {@link org.mockito.MockitoAnnotations}33 *34 * <pre class="code"><code class="java">35 * <b>&#064;Listeners(MockitoTestNGListener.class)</b>36 * public class ExampleTest {37 *38 * &#064;Mock39 * private List list;40 *41 * &#064;Test42 * public void shouldDoSomething() {43 * list.add(100);44 * }45 * }46 * </code></pre>47 */48public class MockitoTestNGListener implements IInvokedMethodListener {49 private MockitoBeforeTestNGMethod beforeTest = new MockitoBeforeTestNGMethod();50 private MockitoAfterTestNGMethod afterTest = new MockitoAfterTestNGMethod();51 public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {52 if (hasMockitoTestNGListenerInTestHierarchy(testResult.getTestClass().getRealClass())) {53 beforeTest.applyFor(method, testResult);54 }55 }56 public void afterInvocation(IInvokedMethod method, ITestResult testResult) {57 if (hasMockitoTestNGListenerInTestHierarchy(testResult.getTestClass().getRealClass())) {58 afterTest.applyFor(method, testResult);59 }60 }61 protected boolean hasMockitoTestNGListenerInTestHierarchy(Class<?> testClass) {62 for (Class<?> clazz = testClass; clazz != Object.class; clazz = clazz.getSuperclass()) {63 if (hasMockitoTestNGListener(clazz)) {64 return true;65 }66 }67 return false;68 }69 protected boolean hasMockitoTestNGListener(Class<?> clazz) {70 Listeners listeners = clazz.getAnnotation(Listeners.class);71 if (listeners == null) {72 return false;...

Full Screen

Full Screen

Source:EventsTest.java Github

copy

Full Screen

...9class EventsTest extends IntegrationFluentTest {10 @Test11 void clickOn() {12 ElementListener beforeListener = Mockito.mock(ElementListener.class);13 ElementListener afterListener = Mockito.mock(ElementListener.class);14 events().beforeClickOn(beforeListener);15 events().afterClickOn(afterListener);16 goTo(DEFAULT_URL);17 $("button").click();18 Mockito.verify(beforeListener).on(Mockito.any(), Mockito.any());19 Mockito.verify(afterListener).on(Mockito.any(), Mockito.any());20 }21 @Test22 void findBy() {23 FindByListener beforeListener = Mockito.mock(FindByListener.class);24 FindByListener afterListener = Mockito.mock(FindByListener.class);25 events().beforeFindBy(beforeListener);26 events().afterFindBy(afterListener);27 goTo(DEFAULT_URL);28 el("button").now();29 Mockito.verify(beforeListener)30 .on(Mockito.any(), Mockito.any(), Mockito.any());31 Mockito.verify(afterListener)32 .on(Mockito.any(), Mockito.any(), Mockito.any());33 }34 @Test35 void navigate() {36 NavigateAllListener beforeListener = Mockito.mock(NavigateAllListener.class);37 NavigateAllListener afterListener = Mockito.mock(NavigateAllListener.class);38 events().beforeNavigate(beforeListener);39 events().afterNavigate(afterListener);40 goTo(DEFAULT_URL);41 Mockito.verify(beforeListener, Mockito.times(1))42 .on(Mockito.eq(DEFAULT_URL), Mockito.any(), Mockito.any());43 Mockito.verify(afterListener, Mockito.times(1))44 .on(Mockito.eq(DEFAULT_URL), Mockito.any(), Mockito.any());45 getDriver().navigate().refresh();46 Mockito.verify(beforeListener, Mockito.times(1))47 .on(Mockito.isNull(), Mockito.any(), Mockito.eq(NavigateAllListener.Direction.REFRESH));48 Mockito.verify(afterListener, Mockito.times(1))49 .on(Mockito.isNull(), Mockito.any(), Mockito.eq(NavigateAllListener.Direction.REFRESH));50 }51 @Test52 void refresh() {53 NavigateListener beforeListener = Mockito.mock(NavigateListener.class);54 NavigateListener afterListener = Mockito.mock(NavigateListener.class);55 events().beforeNavigateRefresh(beforeListener);56 events().afterNavigateRefresh(afterListener);57 goTo(DEFAULT_URL);58 Mockito.verify(beforeListener, Mockito.times(0)).on(Mockito.any());59 Mockito.verify(afterListener, Mockito.times(0)).on(Mockito.any());60 getDriver().navigate().refresh();61 Mockito.verify(beforeListener, Mockito.times(1)).on(Mockito.any());62 Mockito.verify(afterListener, Mockito.times(1)).on(Mockito.any());63 }64}...

Full Screen

Full Screen

after

Using AI Code Generation

copy

Full Screen

1public class MockitoExample {2 public static void main(String[] args) {3 List mockedList = mock(List.class);4 mockedList.add("one");5 mockedList.clear();6 verify(mockedList).add("one");7 verify(mockedList).clear();8 }9}10public class MockitoExample {11 public static void main(String[] args) {12 List mockedList = mock(List.class);13 doThrow(new RuntimeException()).when(mockedList).clear();14 mockedList.clear();15 }16}17 at java.util.List.clear(List.java:119)18 at MockitoExample.main(MockitoExample.java:10)

Full Screen

Full Screen

after

Using AI Code Generation

copy

Full Screen

1public class Foo {2 public String getBar() {3 return "bar";4 }5}6public class FooTest {7 public void testFoo() {8 Foo foo = mock(Foo.class);9 when(foo.getBar()).thenReturn("bar");10 assertEquals("bar", foo.getBar());11 }12}13public class Foo {14 public String getBar() {15 return "bar";16 }17}18public class FooTest {19 public void testFoo() {20 Foo foo = mock(Foo.class);21 when(foo.getBar()).thenReturn("bar");22 assertEquals("bar", foo.getBar());23 }24}25public class Foo {26 public String getBar() {27 return "bar";28 }29}30public class FooTest {31 public void testFoo() {32 Foo foo = mock(Foo.class);33 when(foo.getBar()).thenReturn("bar");34 assertEquals("bar", foo.getBar());35 }36}37public class Foo {38 public String getBar() {39 return "bar";40 }41}42public class FooTest {43 public void testFoo() {44 Foo foo = mock(Foo.class);45 when(foo.getBar()).thenReturn("bar");46 assertEquals("bar", foo.getBar());47 }48}49public class Foo {50 public String getBar() {51 return "bar";52 }53}54public class FooTest {55 public void testFoo() {56 Foo foo = mock(Foo.class);57 when(foo.getBar()).thenReturn("bar");58 assertEquals("bar", foo.getBar());59 }60}61public class Foo {62 public String getBar() {63 return "bar";64 }65}66public class FooTest {67 public void testFoo() {68 Foo foo = mock(Foo.class);69 when(foo.getBar()).thenReturn("bar");70 assertEquals("bar", foo.getBar());71 }72}

Full Screen

Full Screen

after

Using AI Code Generation

copy

Full Screen

1package com.acktutorial.mock;2import static org.mockito.Mockito.*;3import java.util.LinkedList;4import org.junit.Test;5import junit.framework.TestCase;6public class MockitoTest extends TestCase {7public void test() {8LinkedList mockedList = mock(LinkedList.class);9when(mockedList.get(0)).thenReturn("first");10System.out.println(mockedList.get(0));11System.out.println(mockedList.get(999));12}13}

Full Screen

Full Screen

after

Using AI Code Generation

copy

Full Screen

1public interface TestInterface {2 public void test();3}4public class TestClass {5 public void test() {6 System.out.println("test");7 }8}9public class TestClass2 {10 public void test() {11 System.out.println("test2");12 }13}14public class TestClass3 {15 public void test() {16 System.out.println("test3");17 }18}19public class TestClass4 {20 public void test() {21 System.out.println("test4");22 }23}24public class TestClass5 {25 public void test() {26 System.out.println("test5");27 }28}29public class TestClass6 {30 public void test() {31 System.out.println("test6");32 }33}34public class TestClass7 {35 public void test() {36 System.out.println("test7");37 }38}39public class TestClass8 {40 public void test() {41 System.out.println("test8");42 }43}44public class TestClass9 {45 public void test() {46 System.out.println("test9");47 }48}49public class TestClass10 {50 public void test() {51 System.out.println("test10");52 }53}

Full Screen

Full Screen

after

Using AI Code Generation

copy

Full Screen

1package org.mockito;2public class Mockito {3 public static <T> T after(long millis) {4 return null;5 }6}7Example 2: How to use Mockito.after() method?8import static org.mockito.Mockito.*;9import static org.junit.Assert.*;10import java.util.List;11import org.junit.Test;12import org.mockito.ArgumentCaptor;13import org.mockito.InOrder;14import org.mockito.Mockito;15public class MockitoAfterTest {16 List mockedList = mock(List.class);17 public void test() {18 mockedList.add("one");19 mockedList.clear();20 verify(mockedList).add("one");21 verify(mockedList).clear();22 verify(mockedList).add("two");23 }24 public void test1() {25 mockedList.add("one");26 mockedList.clear();27 verify(mockedList, after(100).atLeastOnce()).add("one");28 verify(mockedList, after(100).atLeastOnce()).clear();29 verify(mockedList, after(100).atLeastOnce()).add("two");30 }31}32mockedList.add("two");33-> at MockitoAfterTest.test(MockitoAfterTest.java:28)34Example 3: How to use Mockito.after() method?35import static org.mockito.Mockito.*;36import static org.junit.Assert.*;37import java.util.List;38import org.junit.Test;39import org.mockito.ArgumentCaptor;40import org.mockito.InOrder;41import org.mockito.Mockito;42public class MockitoAfterTest {43 List mockedList = mock(List.class);44 public void test() {45 mockedList.add("one");46 mockedList.clear();47 verify(mockedList).add("one");

Full Screen

Full Screen

after

Using AI Code Generation

copy

Full Screen

1import static org.mockito.Mockito.*;2import org.mockito.invocation.*;3import org.mockito.stubbing.*;4public class 1 {5 public static void main(String[] args) {6 TestClass test = mock(TestClass.class);7 when(test.method()).thenReturn("Hello World");8 test.method();9 verify(test).method();10 }11}12import static org.mockito.Mockito.*;13import org.mockito.invocation.*;14import org.mockito.stubbing.*;15public class 2 {16 public static void main(String[] args) {17 TestClass test = mock(TestClass.class);18 when(test.method()).thenReturn("Hello World");19 test.method();20 verify(test).method();21 }22}23import static org.mockito.Mockito.*;24import org.mockito.invocation.*;25import org.mockito.stubbing.*;26public class 3 {27 public static void main(String[] args) {28 TestClass test = mock(TestClass.class);29 when(test.method()).thenReturn("Hello World");30 test.method();31 verify(test).method();32 }33}34import static org.mockito.Mockito.*;35import org.mockito.invocation.*;36import org.mockito.stubbing.*;37public class 4 {38 public static void main(String[] args) {39 TestClass test = mock(TestClass.class);40 when(test.method()).thenReturn("Hello World");41 test.method();42 verify(test).method();43 }44}45import static org.mockito.Mockito

Full Screen

Full Screen

after

Using AI Code Generation

copy

Full Screen

1verify(mockedList).add("one");2verify(mockedList, times(1)).add("one");3verify(mockedList, atLeastOnce()).add("one");4verify(mockedList, atLeast(1)).add("one");5verify(mockedList, atMost(1)).add("one");6verify(mockedList, never()).add("two");7doThrow(new RuntimeException()).when(mockedList).clear();8verify(mockedList, timeout(100)).add("one");9verify(mockedList, timeout(100).times(1)).add("one");10verify(mockedList, timeout(100).atLeastOnce()).add("one");11verify(mockedList, timeout(100).atLeast(1)).add("one");12verify(mockedList, timeout(100).atMost(1)).add("one");13verify(mockedList, timeout(100).never()).add("two");

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful