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

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

Source:OfficalTest_Part_1.java Github

copy

Full Screen

...12import static org.mockito.Mockito.atMost;13import static org.mockito.Mockito.doThrow;14import static org.mockito.Mockito.inOrder;15import static org.mockito.Mockito.mock;16import static org.mockito.Mockito.never;17import static org.mockito.Mockito.times;18import static org.mockito.Mockito.verify;19import static org.mockito.Mockito.verifyNoMoreInteractions;20import static org.mockito.Mockito.verifyZeroInteractions;21import static org.mockito.Mockito.when;22public class OfficalTest_Part_1 {23 /*24 * 关于默认值25 * 1、 默认情况下,对于所有的方法来说,都将有一个默认的值被返回,26 * 例如对于int\Integer来说是0,对于boolean\Boolean来说是false27 * 2、虽然默认值,可以通过代码进行覆盖,但是过多的覆盖的动作,将会产生更多的代码量28 * 3、一旦被复写之后,无论调用多少次,都将返回复写之后的值29 * 4、最后,存根数据是非常重要的,尤其是当时你使用相同的参数,调用的相同的方法修改默认的值时。30 * 还有就是存根数据的顺序很重要,但是它却很少有意义,例如 当使用完全相同的方法调用时,有时候使用参数匹配器等情况时。31 */32 /**33 * {@see Mockito34 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#235 * }36 */37 @Test38 public void step_2() {39 LinkedList mockedLinkList = mock(LinkedList.class);40 when(mockedLinkList.get(0)).thenReturn("first value");41 when(mockedLinkList.get(1)).thenThrow(new RuntimeException());42 //following prints "first"43 System.out.println(mockedLinkList.get(0));44 //following throws runtime exception45// System.out.println(mockedLinkList.get(1));46 //following prints "null" because get(999) was not stubbed47 System.out.println(mockedLinkList.get(999));48 //Although it is possible to verify a stubbed invocation, usually it's just redundant49 //If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).50 //If your code doesn't care what get(0) returns, then it should not be stubbed. Not convinced? See here.51 verify(mockedLinkList).get(0);52// verify(mockedLinkList).get(1);53 }54 /*55 * Mockito可以使用anyX()来替代任何的参数,但是如果需要自定义参数,那么就需要使用到 argument matchers56 * 使用ArgumentMatcher.argThat(matcher)方法,可以帮助我们校验相应的参数是否满足条件,从而验证有效性57 * 实际上所有的any方法,都是实现了相应的Matcher58 * 需要注意的是,如果你在调用相应的方法参数的时候使用了any方法,也就是说使用了Matcher,那么所有的方法都必须59 * 使用argument matchers60 * verify(mock).someMethod(anyInt(), anyString(), eq("third argument"));61 * //above is correct - eq() is also an argument matcher62 * verify(mock).someMethod(anyInt(), anyString(), "third argument");63 * //above is incorrect -64 * exception will be thrown because third argument is given without an argument matcher.65 */66 /**67 * {@see Mockito68 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#369 * }70 * {@see AdditionalMatchers71 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/AdditionalMatchers.html72 * }73 * [@see ArgumentMatchers74 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/ArgumentMatchers.html75 * }76 * {@see MockitoHamcrest77 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/hamcrest/MockitoHamcrest.html78 * }79 */80 @Test81 public void step_3() {82 LinkedList mockedList = mock(LinkedList.class);83 //stubbing using built-in anyInt() argument matcher84 when(mockedList.get(anyInt())).thenReturn("element");85 //stubbing using custom matcher (let's say isValid() returns your own matcher implementation):86 when(mockedList.contains(argThat(isValid()))).thenReturn(true);87 //following prints "element"88 System.out.println(mockedList.get(999));89 //you can also verify using an argument matcher90 verify(mockedList).get(anyInt());91 mockedList.add("element");92 //argument matchers can also be written as Java 8 Lambdas93// verify(mockedList).add(argThat(someString -> someString.length() > 5));94 verify(mockedList).add(argThat(new ArgumentMatcher<String>() {95 @Override96 public boolean matches(String argument) {97 return argument.length() > 5;98 }99 }));100 anyObject();101 }102 private ArgumentMatcher isValid() {103 return new ArgumentMatcher<String>() {104 @Override105 public boolean matches(String argument) {106 return argument.equals("element");107 }108 };109 }110 /*111 * 默认情况下,time(1)是默认被使用的,相应的方法是隐藏的,因此无需调用112 * 如果使用atLeast方法,可以校验至少执行了多少次113 * 如果使用atMost 方法,可以校验至多运行了多少次114 * never()代表,依次都没有运行115 */116 /**117 * {@see Verifying exact number of invocations / at least x / never118 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#4119 * }120 */121 @Test122 public void step_4() {123 LinkedList<Object> mockedList = mock(LinkedList.class);124 //using mock125 mockedList.add("once");126 mockedList.add("twice");127 mockedList.add("twice");128 mockedList.add("three times");129 mockedList.add("three times");130 mockedList.add("three times");131 //following two verifications work exactly the same - times(1) is used by default132 verify(mockedList).add("once");133 verify(mockedList, times(1)).add("once");134 //exact number of invocations verification135 verify(mockedList, times(2)).add("twice");136 verify(mockedList, times(3)).add("three times");137 //verification using never(). never() is an alias to times(0)138 verify(mockedList, never()).add("never happened");139 //verification using atLeast()/atMost()140 verify(mockedList, atLeastOnce()).add("three times");141 verify(mockedList, atLeast(2)).add("five times");142 verify(mockedList, atMost(5)).add("three times");143 }144 /*145 * 可以通过doThrow方法抛出相应的异常。146 * 下面的语句就表示 党执行mockedList执行clear()方法的时候,将抛出一个异常147 */148 /**149 * {@see Stubbing void methods with exceptions150 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#5151 * }152 */153 @Test154 public void step_5(){155 LinkedList mockedList = mock(LinkedList.class);156 doThrow(new RuntimeException()).when(mockedList).clear();157 //following throws RuntimeException:158 mockedList.clear();159 }160 /*161 * 使用inOrder可以帮助你来校验是否是顺序执行了需要测试的内容162 * 同时,你也可以通过InOrder对象,只传递与按顺序验证相关的mocks163 */164 /**165 * {@see Mockito166 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#6167 * }168 */169 @Test170 public void step_6() {171 // A. Single mock whose methods must be invoked in a particular order172 List<String> singleMock = mock(List.class);173 //using a single mock174 singleMock.add("was added first");175 singleMock.add("was added second");176 //create an inOrder verifier for a single mock177 InOrder inOrder = inOrder(singleMock);178 //following will make sure that add is first called with "was added first, then with "was added second"179 inOrder.verify(singleMock).add("was added first");180 inOrder.verify(singleMock).add("was added second");181 // B. Multiple mocks that must be used in a particular order182 List<String> firstMock = mock(List.class);183 List<String> secondMock = mock(List.class);184 //using mocks185 firstMock.add("was called first");186 secondMock.add("was called second");187 //create inOrder object passing any mocks that need to be verified in order188 InOrder anotherOrder = inOrder(secondMock,firstMock);189 //following will make sure that firstMock was called before secondMock190 anotherOrder.verify(firstMock).add("was called first");191 anotherOrder.verify(secondMock).add("was called second");192 // Oh, and A + B can be mixed together at will193 }194 /*195 * Making sure interaction(s) never happened on mock196 * 确认相互的测试不会产生影响197 */198 /**199 * {@see Mockito200 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#7201 * }202 */203 @Test204 public void step_7() {205 LinkedList<String> mockOne = mock(LinkedList.class);206 LinkedList<String> mockTwo = mock(LinkedList.class);207 LinkedList<String> mockThree = mock(LinkedList.class);208 //using mocks - only mockOne is interacted209 mockOne.add("one");210 //ordinary verification211 verify(mockOne).add("one");212 //verify that method was never called on a mock213 verify(mockOne, never()).add("two");214 //verify that other mocks were not interacted215 verifyZeroInteractions(mockTwo, mockThree);216 }217 /*218 * Finding redundant invocations219 * 通过使用verifyNoMoreInteractions确保相应的调用只执行一次220 * 同时不建议在每个测试方法中使用verifyNoMoreInteractions()。221 * 如果调用never()方法,则会更加明确的表明相应的意图222 */223 /**224 * {@see Mockito225 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#8226 * }227 */228 @Test229 public void step_8() {230 LinkedList<String> mockedList = mock(LinkedList.class);231 //using mocks232 mockedList.add("one");233 mockedList.add("two");234 verify(mockedList).add("one");235 verify(mockedList).add("two");...

Full Screen

Full Screen

Source:MAsyncTaskTest.java Github

copy

Full Screen

...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) {220 return eqBackendError(BackendCommunicationExceptionWithContent.class, innerException, content);221 }...

Full Screen

Full Screen

Source:LeadershipTasksCoordinatorUnitTests.java Github

copy

Full Screen

...73 Mockito.when(this.task3.getTrigger()).thenReturn(task3Trigger);74 final OnGrantedEvent event = new OnGrantedEvent(this, null, "blah");75 this.coordinator.onLeaderEvent(event);76 Mockito.verify(this.scheduler, Mockito.times(1)).scheduleAtFixedRate(this.task1, task1Period);77 Mockito.verify(this.task1, Mockito.never()).getFixedDelay();78 Mockito.verify(this.task1, Mockito.never()).getTrigger();79 Mockito.verify(this.scheduler, Mockito.times(1)).scheduleWithFixedDelay(this.task2, task2Period);80 Mockito.verify(this.task2, Mockito.never()).getFixedRate();81 Mockito.verify(this.task2, Mockito.never()).getTrigger();82 Mockito.verify(this.scheduler, Mockito.times(1)).schedule(this.task3, task3Trigger);83 Mockito.verify(this.task3, Mockito.never()).getFixedRate();84 Mockito.verify(this.task3, Mockito.never()).getFixedDelay();85 //Make sure a second OnGrantedEvent doesn't do anything if it's already running86 this.coordinator.onLeaderEvent(event);87 Mockito.verify(this.scheduler, Mockito.times(1)).scheduleAtFixedRate(this.task1, task1Period);88 Mockito.verify(this.scheduler, Mockito.times(1)).scheduleWithFixedDelay(this.task2, task2Period);89 Mockito.verify(this.scheduler, Mockito.times(1)).schedule(this.task3, task3Trigger);90 }91 /**92 * Make sure all leadership activities are stopped when leadership is revoked.93 */94 @Test95 @SuppressWarnings("unchecked")96 public void canStopLeadershipTasks() {97 final long task1Period = 13238;98 Mockito.when(this.task1.getScheduleType()).thenReturn(GenieTaskScheduleType.FIXED_RATE);99 Mockito.when(this.task1.getFixedRate()).thenReturn(task1Period);100 final long task2Period = 3891082;101 Mockito.when(this.task2.getScheduleType()).thenReturn(GenieTaskScheduleType.FIXED_DELAY);102 Mockito.when(this.task2.getFixedDelay()).thenReturn(task2Period);103 final Trigger task3Trigger = Mockito.mock(Trigger.class);104 Mockito.when(this.task3.getScheduleType()).thenReturn(GenieTaskScheduleType.TRIGGER);105 Mockito.when(this.task3.getTrigger()).thenReturn(task3Trigger);106 final ScheduledFuture future1 = Mockito.mock(ScheduledFuture.class);107 Mockito.when(future1.cancel(true)).thenReturn(true);108 Mockito.when(this.scheduler.scheduleAtFixedRate(this.task1, task1Period)).thenReturn(future1);109 final ScheduledFuture future2 = Mockito.mock(ScheduledFuture.class);110 Mockito.when(future2.cancel(true)).thenReturn(true);111 Mockito.when(this.scheduler.scheduleWithFixedDelay(this.task2, task2Period)).thenReturn(future2);112 final ScheduledFuture future3 = Mockito.mock(ScheduledFuture.class);113 Mockito.when(future3.cancel(true)).thenReturn(false);114 Mockito.when(this.scheduler.schedule(this.task3, task3Trigger)).thenReturn(future3);115 final OnGrantedEvent grantedEvent = new OnGrantedEvent(this, null, "blah");116 this.coordinator.onLeaderEvent(grantedEvent);117 Mockito.verify(this.scheduler, Mockito.times(1)).scheduleAtFixedRate(this.task1, task1Period);118 Mockito.verify(this.task1, Mockito.never()).getFixedDelay();119 Mockito.verify(this.task1, Mockito.never()).getTrigger();120 Mockito.verify(this.scheduler, Mockito.times(1)).scheduleWithFixedDelay(this.task2, task2Period);121 Mockito.verify(this.task2, Mockito.never()).getFixedRate();122 Mockito.verify(this.task2, Mockito.never()).getTrigger();123 Mockito.verify(this.scheduler, Mockito.times(1)).schedule(this.task3, task3Trigger);124 Mockito.verify(this.task3, Mockito.never()).getFixedRate();125 Mockito.verify(this.task3, Mockito.never()).getFixedDelay();126 // Should now be running127 final OnRevokedEvent revokedEvent = new OnRevokedEvent(this, null, "blah");128 this.coordinator.onLeaderEvent(revokedEvent);129 Mockito.verify(future1, Mockito.times(1)).cancel(true);130 Mockito.verify(future2, Mockito.times(1)).cancel(true);131 Mockito.verify(future3, Mockito.times(1)).cancel(true);132 // Call again to make sure nothing is invoked even though they were cancelled133 this.coordinator.onLeaderEvent(revokedEvent);134 Mockito.verify(future1, Mockito.times(1)).cancel(true);135 Mockito.verify(future2, Mockito.times(1)).cancel(true);136 Mockito.verify(future3, Mockito.times(1)).cancel(true);137 }138 /**139 * Make sure unhandled commands are ignored.140 */141 @Test142 public void doesIgnoreUnknownEvent() {143 final AbstractLeaderEvent leaderEvent = new AbstractLeaderEvent(this) {144 /**145 * Gets the {@link Context} associated with this event.146 *147 * @return the context148 */149 @Override150 public Context getContext() {151 return new Context() {152 @Override153 public boolean isLeader() {154 return false;155 }156 @Override157 public void yield() {158 }159 };160 }161 };162 this.coordinator.onLeaderEvent(leaderEvent);163 Mockito.verify(164 this.scheduler, Mockito.never()).scheduleAtFixedRate(Mockito.any(Runnable.class), Mockito.anyLong()165 );166 }167}...

Full Screen

Full Screen

Source:LeadershipTasksCoordinatorTest.java Github

copy

Full Screen

...69 Mockito.when(this.task3.getTrigger()).thenReturn(task3Trigger);70 final OnGrantedEvent event = new OnGrantedEvent(this, null, "blah");71 this.coordinator.onLeaderEvent(event);72 Mockito.verify(this.scheduler, Mockito.times(1)).scheduleAtFixedRate(this.task1, task1Period);73 Mockito.verify(this.task1, Mockito.never()).getFixedDelay();74 Mockito.verify(this.task1, Mockito.never()).getTrigger();75 Mockito.verify(this.scheduler, Mockito.times(1)).scheduleWithFixedDelay(this.task2, task2Period);76 Mockito.verify(this.task2, Mockito.never()).getFixedRate();77 Mockito.verify(this.task2, Mockito.never()).getTrigger();78 Mockito.verify(this.scheduler, Mockito.times(1)).schedule(this.task3, task3Trigger);79 Mockito.verify(this.task3, Mockito.never()).getFixedRate();80 Mockito.verify(this.task3, Mockito.never()).getFixedDelay();81 //Make sure a second OnGrantedEvent doesn't do anything if it's already running82 this.coordinator.onLeaderEvent(event);83 Mockito.verify(this.scheduler, Mockito.times(1)).scheduleAtFixedRate(this.task1, task1Period);84 Mockito.verify(this.scheduler, Mockito.times(1)).scheduleWithFixedDelay(this.task2, task2Period);85 Mockito.verify(this.scheduler, Mockito.times(1)).schedule(this.task3, task3Trigger);86 }87 /**88 * Make sure all leadership activities are stopped when leadership is revoked.89 */90 @Test91 @SuppressWarnings("unchecked")92 void canStopLeadershipTasks() {93 final long task1Period = 13238;94 Mockito.when(this.task1.getScheduleType()).thenReturn(GenieTaskScheduleType.FIXED_RATE);95 Mockito.when(this.task1.getFixedRate()).thenReturn(task1Period);96 final long task2Period = 3891082;97 Mockito.when(this.task2.getScheduleType()).thenReturn(GenieTaskScheduleType.FIXED_DELAY);98 Mockito.when(this.task2.getFixedDelay()).thenReturn(task2Period);99 final Trigger task3Trigger = Mockito.mock(Trigger.class);100 Mockito.when(this.task3.getScheduleType()).thenReturn(GenieTaskScheduleType.TRIGGER);101 Mockito.when(this.task3.getTrigger()).thenReturn(task3Trigger);102 final ScheduledFuture future1 = Mockito.mock(ScheduledFuture.class);103 Mockito.when(future1.cancel(true)).thenReturn(true);104 Mockito.when(this.scheduler.scheduleAtFixedRate(this.task1, task1Period)).thenReturn(future1);105 final ScheduledFuture future2 = Mockito.mock(ScheduledFuture.class);106 Mockito.when(future2.cancel(true)).thenReturn(true);107 Mockito.when(this.scheduler.scheduleWithFixedDelay(this.task2, task2Period)).thenReturn(future2);108 final ScheduledFuture future3 = Mockito.mock(ScheduledFuture.class);109 Mockito.when(future3.cancel(true)).thenReturn(false);110 Mockito.when(this.scheduler.schedule(this.task3, task3Trigger)).thenReturn(future3);111 final OnGrantedEvent grantedEvent = new OnGrantedEvent(this, null, "blah");112 this.coordinator.onLeaderEvent(grantedEvent);113 Mockito.verify(this.scheduler, Mockito.times(1)).scheduleAtFixedRate(this.task1, task1Period);114 Mockito.verify(this.task1, Mockito.never()).getFixedDelay();115 Mockito.verify(this.task1, Mockito.never()).getTrigger();116 Mockito.verify(this.scheduler, Mockito.times(1)).scheduleWithFixedDelay(this.task2, task2Period);117 Mockito.verify(this.task2, Mockito.never()).getFixedRate();118 Mockito.verify(this.task2, Mockito.never()).getTrigger();119 Mockito.verify(this.scheduler, Mockito.times(1)).schedule(this.task3, task3Trigger);120 Mockito.verify(this.task3, Mockito.never()).getFixedRate();121 Mockito.verify(this.task3, Mockito.never()).getFixedDelay();122 // Should now be running123 final OnRevokedEvent revokedEvent = new OnRevokedEvent(this, null, "blah");124 this.coordinator.onLeaderEvent(revokedEvent);125 Mockito.verify(future1, Mockito.times(1)).cancel(true);126 Mockito.verify(future2, Mockito.times(1)).cancel(true);127 Mockito.verify(future3, Mockito.times(1)).cancel(true);128 // Call again to make sure nothing is invoked even though they were cancelled129 this.coordinator.onLeaderEvent(revokedEvent);130 Mockito.verify(future1, Mockito.times(1)).cancel(true);131 Mockito.verify(future2, Mockito.times(1)).cancel(true);132 Mockito.verify(future3, Mockito.times(1)).cancel(true);133 }134 /**135 * Make sure unhandled commands are ignored.136 */137 @Test138 void doesIgnoreUnknownEvent() {139 final AbstractLeaderEvent leaderEvent = new AbstractLeaderEvent(this) {140 /**141 * Gets the {@link Context} associated with this event.142 *143 * @return the context144 */145 @Override146 public Context getContext() {147 return new Context() {148 @Override149 public boolean isLeader() {150 return false;151 }152 @Override153 public void yield() {154 }155 };156 }157 };158 this.coordinator.onLeaderEvent(leaderEvent);159 Mockito.verify(160 this.scheduler, Mockito.never()).scheduleAtFixedRate(Mockito.any(Runnable.class), Mockito.anyLong()161 );162 }163}...

Full Screen

Full Screen

Source:VerificationListenerCallBackTest.java Github

copy

Full Screen

...33 mockitoFramework.addListener(listener);34 Method invocationWanted = Foo.class.getDeclaredMethod("doSomething", String.class);35 Foo foo = mock(Foo.class);36 // when37 VerificationMode never = never();38 verify(foo, never).doSomething("");39 // then40 assertThat(listener).is(notifiedFor(foo, never, invocationWanted));41 }42 @Test43 public void should_call_all_listeners_on_verify() throws NoSuchMethodException {44 // given45 RememberingListener listener1 = new RememberingListener();46 RememberingListener2 listener2 = new RememberingListener2();47 Mockito.framework().addListener(listener1).addListener(listener2);48 Method invocationWanted = Foo.class.getDeclaredMethod("doSomething", String.class);49 Foo foo = mock(Foo.class);50 // when51 VerificationMode never = never();52 verify(foo, never).doSomething("");53 // then54 assertThat(listener1).is(notifiedFor(foo, never, invocationWanted));55 assertThat(listener2).is(notifiedFor(foo, never, invocationWanted));56 }57 @Test58 public void should_not_call_listener_when_verify_was_called_incorrectly() {59 // when60 VerificationListener listener = mock(VerificationListener.class);61 framework().addListener(listener);62 Foo foo = null;63 try {64 verify(foo).doSomething("");65 fail("Exception expected.");66 } catch (Exception e) {67 // then68 verify(listener, never()).onVerification(any(VerificationEvent.class));69 }70 }71 @Test72 public void should_notify_when_verification_throws_type_error() {73 // given74 RememberingListener listener = new RememberingListener();75 MockitoFramework mockitoFramework = Mockito.framework();76 mockitoFramework.addListener(listener);77 Foo foo = mock(Foo.class);78 // when79 try {80 verify(foo).doSomething("");81 fail("Exception expected.");82 } catch (Throwable e) {...

Full Screen

Full Screen

Source:JSDebuggerWebSocketClientTest.java Github

copy

Full Screen

...59 @Test60 public void test_onMessage_WithInvalidContentType_ShouldNotTriggerCallbacks() throws Exception {61 JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient());62 client.onMessage(null, ByteString.encodeUtf8("{\"replyID\":0, \"result\":\"OK\"}"));63 PowerMockito.verifyPrivate(client, never())64 .invoke("triggerRequestSuccess", anyInt(), anyString());65 PowerMockito.verifyPrivate(client, never()).invoke("triggerRequestFailure", anyInt(), any());66 }67 @Test68 public void test_onMessage_WithoutReplyId_ShouldNotTriggerCallbacks() throws Exception {69 JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient());70 client.onMessage(null, "{\"result\":\"OK\"}");71 PowerMockito.verifyPrivate(client, never())72 .invoke("triggerRequestSuccess", anyInt(), anyString());73 PowerMockito.verifyPrivate(client, never()).invoke("triggerRequestFailure", anyInt(), any());74 }75 @Test76 public void test_onMessage_With_Null_ReplyId_ShouldNotTriggerCallbacks() throws Exception {77 JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient());78 client.onMessage(null, "{\"replyID\":null, \"result\":\"OK\"}");79 PowerMockito.verifyPrivate(client, never())80 .invoke("triggerRequestSuccess", anyInt(), anyString());81 PowerMockito.verifyPrivate(client, never()).invoke("triggerRequestFailure", anyInt(), any());82 }83 @Test84 public void test_onMessage_WithResult_ShouldTriggerRequestSuccess() throws Exception {85 JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient());86 client.onMessage(null, "{\"replyID\":0, \"result\":\"OK\"}");87 PowerMockito.verifyPrivate(client).invoke("triggerRequestSuccess", 0, "OK");88 PowerMockito.verifyPrivate(client, never()).invoke("triggerRequestFailure", anyInt(), any());89 }90 @Test91 public void test_onMessage_With_Null_Result_ShouldTriggerRequestSuccess() throws Exception {92 JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient());93 client.onMessage(null, "{\"replyID\":0, \"result\":null}");94 PowerMockito.verifyPrivate(client).invoke("triggerRequestSuccess", 0, null);95 PowerMockito.verifyPrivate(client, never()).invoke("triggerRequestFailure", anyInt(), any());96 }97 @Test98 public void test_onMessage_WithError_ShouldCallAbort() throws Exception {99 JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient());100 client.onMessage(null, "{\"replyID\":0, \"error\":\"BOOM\"}");101 PowerMockito.verifyPrivate(client).invoke("abort", eq("BOOM"), isA(JavascriptException.class));102 }103 @Test104 public void test_onMessage_With_Null_Error_ShouldTriggerRequestSuccess() throws Exception {105 JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient());106 client.onMessage(null, "{\"replyID\":0, \"error\":null}");107 PowerMockito.verifyPrivate(client).invoke("triggerRequestSuccess", anyInt(), anyString());108 }109}...

Full Screen

Full Screen

Source:BytecodeDumpServiceTest.java Github

copy

Full Screen

...8import org.mockito.Mock;9import org.mockito.Mockito;10import org.mockito.junit.MockitoJUnitRunner;11import java.util.Collections;12import static org.mockito.Mockito.never;13import static org.mockito.Mockito.times;14/**15 * @author Woonduk Kang(emeroad)16 */17@RunWith(MockitoJUnitRunner.class)18public class BytecodeDumpServiceTest {19 private final String classInternalName = JavaAssistUtils.javaNameToJvmName("java.lang.String");20 @Mock21 private ASMBytecodeDisassembler disassembler;22 @InjectMocks23 private BytecodeDumpService bytecodeDumpService = new ASMBytecodeDumpService(true, true, true, Collections.singletonList(classInternalName));24 @InjectMocks25 private BytecodeDumpService disableBytecodeDumpService = new ASMBytecodeDumpService(false, false, false, Collections.singletonList(classInternalName));26 @Test27 public void dumpBytecode() throws Exception {28 ClassLoader classLoader = ClassLoaderUtils.getDefaultClassLoader();29 byte[] classFile = BytecodeUtils.getClassFile(classLoader, classInternalName);30 bytecodeDumpService.dumpBytecode("testDump", classInternalName, classFile, classLoader);31 Mockito.verify(this.disassembler, times(1)).dumpBytecode(classFile);32 Mockito.verify(this.disassembler, times(1)).dumpVerify(classFile, classLoader);33 Mockito.verify(this.disassembler, times(1)).dumpASM(classFile);34 }35 @Test36 public void dumpBytecode_disable() throws Exception {37 ClassLoader classLoader = ClassLoaderUtils.getDefaultClassLoader();38 byte[] classFile = BytecodeUtils.getClassFile(classLoader, classInternalName);39 disableBytecodeDumpService.dumpBytecode("disableTestDump", classInternalName, classFile, classLoader);40 Mockito.verify(this.disassembler, never()).dumpBytecode(classFile);41 Mockito.verify(this.disassembler, never()).dumpVerify(classFile, classLoader);42 Mockito.verify(this.disassembler, never()).dumpASM(classFile);43 }44 @Test45 public void dumpBytecode_filter() throws Exception {46 ClassLoader classLoader = ClassLoaderUtils.getDefaultClassLoader();47 byte[] classFile = BytecodeUtils.getClassFile(classLoader, classInternalName);48 bytecodeDumpService.dumpBytecode("testDump", "invalidName", classFile, classLoader);49 Mockito.verify(this.disassembler, never()).dumpBytecode(classFile);50 Mockito.verify(this.disassembler, never()).dumpVerify(classFile, classLoader);51 Mockito.verify(this.disassembler, never()).dumpASM(classFile);52 }53}...

Full Screen

Full Screen

Source:TestDoublures.java Github

copy

Full Screen

...4import static org.mockito.Mockito.when;5import java.util.LinkedList;6import static org.mockito.Mockito.verify;7import static org.mockito.Mockito.times;8import static org.mockito.Mockito.never;9import static org.mockito.Mockito.atLeastOnce;10import static org.mockito.Mockito.atLeast;11import static org.mockito.Mockito.atMost;12import static org.junit.Assert.assertEquals;13public class TestDoublures {14 @Test15 public void test_UnPremierStub() {16 User user = mock(User.class); //création de la doublure17 when(user.getLogin()).thenReturn("alice"); //bouchonnage de la doublure18 19 System.out.println(user.getLogin());20 21 assertEquals(user.getLogin(), "alice");22 //assertEquals(user.getLogin(), "bob");23 }24 25 @Test26 public void test_UnPremierMock() {27 User user = mock(User.class);28 when(user.getLogin()).thenReturn("alice");29 System.out.println(user.getLogin());30 System.out.println(user.getLogin());31 verify(user, times(2)).getLogin(); //Vérification de l'affichage appelé 2 fois32 //verify(user).getLogin(); //verifier que la méthode a été appelé33 34 }35 36 @Test37 public void test_OptionsVerification() {38 LinkedList<String> mockedList = mock(LinkedList.class);39 mockedList.add("once");40 mockedList.add("twice");41 mockedList.add("twice");42 mockedList.add("three times");43 mockedList.add("three times");44 mockedList.add("three times");45 //following two verifications work exactly the same - times(1) is used by default46 verify(mockedList).add("once");47 verify(mockedList, times(1)).add("once");48 //exact number of invocations verification49 verify(mockedList, times(2)).add("twice");50 verify(mockedList, times(3)).add("three times");51 //verification using never(). never() is an alias to times(0)52 verify(mockedList, never()).add("never happened");53 //verification using atLeast()/atMost()54 verify(mockedList, atLeastOnce()).add("three times");55 verify(mockedList, atLeast(2)).add("three times");56 verify(mockedList, atMost(5)).add("three times");57 }58}...

Full Screen

Full Screen

never

Using AI Code Generation

copy

Full Screen

1package org.kodejava.example.mockito;2import org.junit.Test;3import org.mockito.Mockito;4import java.util.List;5public class NeverTest {6 public void testNever() {7 List<String> list = Mockito.mock(List.class);8 Mockito.verify(list, Mockito.never()).add("Hello");9 }10}

Full Screen

Full Screen

never

Using AI Code Generation

copy

Full Screen

1package com.ack.junit.mockitobasics;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.mockito.Mock;5import org.mockito.runners.MockitoJUnitRunner;6import java.util.List;7import static org.mockito.Mockito.never;8@RunWith(MockitoJUnitRunner.class)9public class MockitoNeverTest {10 private List<String> mockedList;11 public void testNeverMethod() {12 mockedList.add("one");13 mockedList.add("two");14 mockedList.add("three");15 never().verify(mockedList).add("neverCalled");16 }17}18-> at com.ack.junit.mockitobasics.MockitoNeverTest.testNeverMethod(MockitoNeverTest.java:20)19-> at com.ack.junit.mockitobasics.MockitoNeverTest.testNeverMethod(MockitoNeverTest.java:24)20mockedList.add("neverCalled");21-> at com.ack.junit.mockitobasics.MockitoNeverTest.testNeverMethod(MockitoNeverTest.java:20)22mockedList.add("one");23-> at com.ack.junit.mockitobasics.MockitoNeverTest.testNeverMethod(MockitoNeverTest.java:21)24mockedList.add("two");25-> at com.ack.junit.mockitobasics.MockitoNeverTest.testNeverMethod(MockitoNeverTest.java:22)26mockedList.add("three");27-> at com.ack.junit.mockitobasics.MockitoNeverTest.testNeverMethod(MockitoNeverTest.java:23)28testNeverMethod(com.ack.junit.mockitobasics.MockitoNeverTest) Time elapsed: 0.168 sec <<< FAILURE!29-> at com.ack.junit.mockitobasics.MockitoNeverTest.testNeverMethod(MockitoNeverTest.java:20)30-> at com.ack.junit.mockitobasics.MockitoNeverTest.testNeverMethod(MockitoNeverTest.java:24)31mockedList.add("neverCalled");

Full Screen

Full Screen

never

Using AI Code Generation

copy

Full Screen

1import static org.mockito.Mockito.*;2import org.mockito.MockitoAnnotations;3import org.mockito.Mock;4import org.mockito.InjectMocks;5import org.junit.Test;6import org.junit.Before;7import org.junit.runner.RunWith;8import org.mockito.runners.MockitoJUnitRunner;9import java.util.*;10import static org.junit.Assert.*;11import org.junit.Assert;12import org.junit.BeforeClass;13import org.junit.Test;14import org.junit.runner.RunWith;15import org.mockito.Mock;16import org.mockito.Mockito;17import org.mockito.runners.MockitoJUnitRunner;18import org.mockito.internal.matchers.*;19import org.mockito.invocation.*;20import org.mockito.stubbing.*;21import org.mockito.verification.*;22import org.mockito.exceptions.*;23import org.mockito.exceptions.base.*;24import org.mockito.exceptions.verification.*;25import org.mockito.exceptions.verification.junit.*;26import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;27import org.mockito.exceptions.verification.junit.WantedButNotInvoked;28import org.mockito.exceptions.verification.junit.WantedButNotInvokedInOrder;29import org.mockito.exceptions.verification.junit.WantedButNotInvokedWithWantedNumberOfInvocations;30import org.mockito.exceptions.verification.junit.WantedButNotInvokedWithWantedNumberOfInvocationsInOrder;31import org.mockito.exceptions.verification.junit.WantedButNotInvokedWithWantedNumberOfInvocationsInOrder;32import org.mockito.exceptions.verification.junit.WantedButNotInvokedWithWantedNumberOfInvocationsInOrder;33import org.mockito.exceptions.verification.junit.WantedButNotInvokedWithWantedNumberOfInvocationsInOrder;34import org.mockito.exceptions.verification.junit.WantedButNotInvokedWithWantedNumberOfInvocationsInOrder;35import org.mockit

Full Screen

Full Screen

never

Using AI Code Generation

copy

Full Screen

1package org.ksrntheja.javaprograms.eigth.lambdaexpressions;2import java.util.List;3import static org.mockito.Mockito.mock;4import static org.mockito.Mockito.never;5public class MockitoNeverMethod {6 public static void main(String[] args) {7 List mockedList = mock(List.class);8 mockedList.add("one");9 mockedList.clear();10 verify(mockedList).add("one");11 verify(mockedList, never()).add("two");12 }13}

Full Screen

Full Screen

never

Using AI Code Generation

copy

Full Screen

1import org.mockito.Mockito;2import org.mockito.invocation.InvocationOnMock;3import org.mockito.stubbing.Answer;4import java.util.List;5import static org.mockito.Mockito.*;6import static org.junit.Assert.*;7import org.junit.Test;8public class MockitoTest {9 public void test() {10 List mockedList = mock(List.class);11 when(mockedList.get(anyInt())).thenAnswer(new Answer() {12 public Object answer(InvocationOnMock invocation) {13 Object[] args = invocation.getArguments();14 Object mock = invocation.getMock();15 return "called with arguments: " + args;16 }17 });18 System.out.println(mockedList.get(0));19 System.out.println(mockedList.get(999));20 }21}22Next Topic Mockito doThrow() method

Full Screen

Full Screen

never

Using AI Code Generation

copy

Full Screen

1import org.mockito.Mockito;2import org.mockito.invocation.InvocationOnMock;3import org.mockito.stubbing.Answer;4public class 1 {5 public static void main(String[] args) {6 List mock = Mockito.mock(List.class);7 Mockito.when(mock.get(0)).thenReturn("Hello World");8 System.out.println(mock.get(0));9 }10}11import org.mockito.Mockito;12import org.mockito.invocation.InvocationOnMock;13import org.mockito.stubbing.Answer;14public class 1 {15 public static void main(String[] args) {16 List mock = Mockito.mock(List.class);17 Mockito.doThrow(new RuntimeException()).when(mock).clear();18 mock.clear();19 }20}21 at org.mockito.Mockito.doThrow(Mockito.java:140)22 at 1.main(1.java:11)23import org.mockito.Mockito;24import org.mockito.invocation.InvocationOnMock;25import org.mockito.stubbing.Answer;26public class 1 {27 public static void main(String[] args) {28 List mock = Mockito.mock(List.class);29 Mockito.doAnswer(new Answer() {30 public Object answer(InvocationOnMock invocation) {31 Object[] args = invocation.getArguments();32 Object mock = invocation.getMock();33 return "called with arguments: " + args;34 }35 }).when(mock).get(0);36 System.out.println(mock.get(0));37 }38}39The following example shows how to use doNothing() method of org.mockito.Mockito class to define the return value of a method

Full Screen

Full Screen

never

Using AI Code Generation

copy

Full Screen

1import org.mockito.Mockito;2import org.junit.Test;3import static org.mockito.Mockito.*;4import static org.junit.Assert.*;5public class MockitoTest {6 public void test() {7 List mockedList = mock(List.class);8 when(mockedList.get(0)).thenReturn("first");9 when(mockedList.get(1)).thenThrow(new RuntimeException());10 System.out.println(mockedList.get(0));11 System.out.println(mockedList.get(1));12 System.out.println(mockedList.get(999));13 verify(mockedList).get(0);14 }15}

Full Screen

Full Screen

never

Using AI Code Generation

copy

Full Screen

1import static org.mockito.Mockito.*;2import org.mockito.Mockito;3import org.mockito.Mockito.*;4import java.util.*;5import java.io.*;6import java.lang.*;7import java.util.List;8public class 1 {9 public static void main(String[] args) {10 List mockList = mock(List.class);11 ArrayList spyList = spy(ArrayList.class);12 doReturn("Hello").when(mockList).get(0);13 doReturn("Hello").when(spyList).get(0);14 when(mockList.get(0)).thenReturn("Hello");15 when(spyList.get(0)).thenReturn("Hello");16 mockList.get(0);17 spyList.get(0);18 Mockito.when(mockList.get(0)).thenReturn("Hello");19 Mockito.when(spyList.get(0)).thenReturn("Hello");20 Mockito.doReturn("Hello").when(mockList).get(0);21 Mockito.doReturn("Hello").when(spyList).get(0);22 Mockito.doReturn("Hello").when(mockList.get(0));23 Mockito.doReturn("Hello").when(spyList.get(0));24 System.out.println("mockList.get(0) = " + mockList.get(0));25 System.out.println("spyList.get(0) = " + spyList.get(0));26 }27}28mockList.get(0) = Hello29spyList.get(0) = Hello30Recommended Posts: Mockito - when() method31Mockito - doThrow() method32Mockito - doNothing() method33Mockito - doAnswer() method34Mockito - doCallRealMethod() method35Mockito - doReturn() method36Mockito - doThrow() method37Mockito - doNothing() method38Mockito - doAnswer() method39Mockito - doCallRealMethod() method40Mockito - doReturn() method41Mockito - doThrow() method42Mockito - doNothing() method43Mockito - doAnswer() method44Mockito - doCallRealMethod() method

Full Screen

Full Screen

never

Using AI Code Generation

copy

Full Screen

1package org.jmockit;2import org.junit.Assert;3import org.junit.Test;4import org.mockito.Mockito;5import java.util.Iterator;6import java.util.List;7public class Example1 {8 public void test1() {9 List mockList = Mockito.mock(List.class);10 Mockito.when(mockList.get(0)).thenReturn("one");11 Mockito.when(mockList.get(1)).thenReturn("two");12 System.out.println(mockList.get(0));13 Mockito.verify(mockList).get(0);14 }15 public void test2() {16 List mockList = Mockito.mock(List.class);17 Mockito.when(mockList.get(Mockito.anyInt())).thenReturn("element");18 Mockito.when(mockList.contains(Mockito.anyObject())).thenReturn(true);19 System.out.println(mockList.get(999));20 Mockito.verify(mockList).get(Mockito.anyInt());21 }22 public void test3() {23 List mockList = Mockito.mock(List.class);24 Mockito.when(mockList.get(Mockito.anyInt())).thenReturn("element");25 Mockito.when(mockList.contains(Mockito.anyObject())).thenReturn(true);26 System.out.println(mockList.get(999));27 Mockito.verify(mockList).get(Mockito.anyInt());28 }29 public void test4() {30 List mockList = Mockito.mock(List.class);31 Mockito.when(mockList.get(Mockito.anyInt())).thenReturn("element");32 Mockito.when(mockList.contains(Mockito.anyObject())).thenReturn(true);33 System.out.println(mockList.get(999));34 Mockito.verify(mockList).get(Mockito.anyInt());35 }36 public void test5() {

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