Best Mockito code snippet using org.mockito.Mockito.mock
Source:OfficalTest_Part_1.java
1package com.joke.mock.offical_mock;2import org.junit.Test;3import org.mockito.ArgumentMatcher;4import org.mockito.InOrder;5import java.util.LinkedList;6import java.util.List;7import static org.mockito.Mockito.anyInt;8import static org.mockito.Mockito.anyObject;9import static org.mockito.Mockito.argThat;10import static org.mockito.Mockito.atLeast;11import static org.mockito.Mockito.atLeastOnce;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");236 //following verification will fail237 verifyNoMoreInteractions(mockedList);238 }239 /*240 * Shorthand for mocks creation - @Mock annotation241 * 使ç¨@Mockå¯ä»¥å¸®å©æ们æ´å å¿«éçå建ç¸åºçmock对象ï¼åæ¶æ¥ææ´å¥½çå¯è¯»æ§242 */243 /**244 * {@see Mockito245 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#9246 * }247 * {@see MockitoRule248 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/junit/MockitoRule.html249 * }250 * {@see MockitoAnnotations251 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/MockitoAnnotations.html252 * }253 */254 @Test255 public void step_9() {256// public class ArticleManagerTest {257//258// @Mock259// private ArticleCalculator calculator;260// @Mock261// private ArticleDatabase database;262// @Mock263// private UserProvider userProvider;264//265// private ArticleManager manager;266// }267// Important! This needs to be somewhere in the base class or a test runner:268//269// MockitoAnnotations.initMocks(testClass);270 }271 /*272 * Stubbing consecutive calls (iterator-style stubbing)273 * ç»å¤æ¬¡è°ç¨åæ ·çæ¹æ³ï¼æ·»å ä¸åçè¿åå¼274 * éè¦æ³¨æçæ¯å¦æå¤æ¬¡ä½¿ç¨åæ ·åæ°çæ¹æ³ï¼ä¹åè°ç¨thenReturnï¼å°ä¼äº§ççæææ¯275 * åä¸ä¸ªä¼è¦çåä¸ä¸ªçè¿åå¼ã276 */277 /**278 * {@see Mockito279 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#10280 * }281 */282 @Test283 public void step_10() {284//285// when(mock.someMethod("some arg"))286// .thenThrow(new RuntimeException())287// .thenReturn("foo");288//289// //First call: throws runtime exception:290// mock.someMethod("some arg");291//292// //Second call: prints "foo"293// System.out.println(mock.someMethod("some arg"));294//295// //Any consecutive call: prints "foo" as well (last stubbing wins).296// System.out.println(mock.someMethod("some arg"));297//298// Alternative, shorter version of consecutive stubbing:299//300// when(mock.someMethod("some arg"))301// .thenReturn("one", "two", "three");302//303// Warning : if instead of chaining .thenReturn() calls, multiple stubbing with the same matchers or arguments is used, then each stubbing will override the previous one:304//305// //TODO:All mock.someMethod("some arg") calls will return "two"306// when(mock.someMethod("some arg"))307// .thenReturn("one")308// when(mock.someMethod("some arg"))309// .thenReturn("two")310 }311}...
Source:OfficalTest_Part_2.java
1package com.joke.mock.offical_mock;2import org.junit.Assert;3import org.junit.Test;4import org.mockito.ArgumentCaptor;5import org.mockito.BDDMockito;6import org.mockito.Mockito;7import org.mockito.invocation.InvocationOnMock;8import org.mockito.stubbing.Answer;9import java.util.ArrayList;10import java.util.Arrays;11import java.util.LinkedList;12import java.util.List;13import static org.mockito.Mockito.CALLS_REAL_METHODS;14import static org.mockito.Mockito.anyInt;15import static org.mockito.Mockito.doAnswer;16import static org.mockito.Mockito.doReturn;17import static org.mockito.Mockito.mock;18import static org.mockito.Mockito.reset;19import static org.mockito.Mockito.spy;20import static org.mockito.Mockito.verify;21import static org.mockito.Mockito.when;22import static org.mockito.Mockito.withSettings;23public class OfficalTest_Part_2 {24 /*25 * Stubbing with callbacks26 * å¯ä»¥ä½¿ç¨Answeræ¥è¿è¡ä¿®æ¹ç¸åºç,æ¯å¦å¨ä¸é¢çä¾åä¸,æ们修æ¹ç¸åºçè¿åå¼,27 * è°ç¨ç¸åºçaddæ¹æ³æ¶ï¼å°±ä¼è¿åæ们èªå®ä¹çç»æ28 * æ好 thenReturn() or thenThrow()çæ¹æ³ï¼æ¥è¿è¡ç¸åºçæµè¯ã29 */30 /**31 * {@see Mockito32 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#1133 * }34 */35 @Test36 public void step_11() {37 final LinkedList mockedLinkList = mock(LinkedList.class);38 when(mockedLinkList.remove(anyInt())).thenAnswer(new Answer<String>() {39 @Override40 public String answer(InvocationOnMock invocation) throws Throwable {41 Object[] arguments = invocation.getArguments();42 Object mock = invocation.getMock();43 return "called with arguments: " + Arrays.toString(arguments);44 }45 });46 System.out.println(mockedLinkList.remove(999));47 }48 /*49 * doReturn()|doThrow()| doAnswer()|doNothing()|doCallRealMethod() family of methods50 *51 */52 /**53 * {@see Mockito54 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#1255 * }56 */57 @Test58 public void step_12() {59 final LinkedList mockedLinkList = mock(LinkedList.class);60 when(mockedLinkList.get(0)).thenReturn(false);61 doAnswer(new Answer<Boolean>() {62 @Override63 public Boolean answer(InvocationOnMock invocation) throws Throwable {64 Object[] arguments = invocation.getArguments();65 Object mock = invocation.getMock();66 return mock == mockedLinkList;67 }68 }).when(mockedLinkList).get(anyInt());69 System.out.println(mockedLinkList.get(0));70 }71 /*72 * å½ä½¿ç¨spyçæ¶åï¼ä¼çæ£è°ç¨ç¸åºçæ¹æ³(é¤é使ç¨å
¶ä»æ段修æ¹ç¸åºçè¿åå¼ï¼ æ¯å¦doXxx())73 * 注æï¼åºå½å°½å¯è½ä»ç»ä½¿ç¨ï¼å¹¶ä¸å°½éå°å°ä½¿ç¨spyï¼æ¯å¦å¨å¤çéçç代ç çæ¶å74 * å¨ä¸ä¸ªçæ£ç对象ä¸ä½¿ç¨Spyï¼å¯ä»¥ç解为âpartial mockingâï¼ä½æ¯å¨1.8ä¹åï¼Mockito并ä¸æ¯çæ£75 * partial mockï¼åå å¨äºï¼æ们认为partial mockæ¯ä»£ç çä¸é¨åãå¨æäºæ¹é¢ï¼æ们åç°äºä½¿ç¨é¨åmocks76 * çåçä¹å¤(ä¾å¦ï¼ç¬¬ä¸æ¹æ¥å£ï¼éç代ç ç临æ¶éæï¼å
¨é¨çæç« ï¼åè以ä¸å
容77 * {@see partial-mocking78 * https://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring/})79 * æä¸ç¹éè¦ç¹å«æ³¨æçæ¯ï¼å¨ä½¿ç¨ when(Object)æ¹æ³è°ç¨spy对象çæ¶åï¼å»ºè®®ä½¿ç¨ä»¥ä¸çæ¹æ³æ¿ä»£doReturn|Answer|Throw()80 * ä¾å¦81 * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)82 * when(spy.get(0)).thenReturn("ArrayList");83 * ç±äºspy并没æåå§åï¼å æ¤å°ä¼æåºç¸åºçå¼å¸¸84 * //You have to use doReturn() for stubbing85 * doReturn("ArrayList").when(spy).get(0);86 *87 */88 /**89 * {@see Mockito90 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#1391 * }92 */93 @Test94 public void step_13() {95 List list = new LinkedList();96 List<String> spy = spy(list);97 //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)98 when(spy.get(0)).thenReturn("ArrayList");99 //You have to use doReturn() for stubbing100 doReturn("ArrayList").when(spy).get(0);101 //optionally, you can stub out some methods:102 when(spy.size()).thenReturn(100);103 //using the spy calls *real* methods104 spy.add("one");105 spy.add("two");106 //prints "one" - the first element of a list107 System.out.println(spy.get(0));108 //size() method was stubbed - 100 is printed109 System.out.println(spy.size());110 //optionally, you can verify111 verify(spy).add("one");112 verify(spy).add("two");113 }114 /*115 * Changing default return values of unstubbed invocations (Since 1.7)116 * æ们å¯ä»¥ç»ç¸åºçè¿åå¼ï¼æå®ä¸ä¸ªé»è®¤çè§åã117 * è¿æ¯æ³å½é«çº§çåè½ï¼å¹¶ä¸å¯¹äºæ§ç³»ç»ï¼æ¥è¯´æ¯é常æ帮å©ç118 * é»è®¤æ
åµä¸ï¼ä½ æ ¹æ¬ä¸éè¦è°ç¨å®119 * æ´å¤çå
容ï¼å¯ä»¥åèé»è®¤çå®ç°ã120 * {@see RETURNS_SMART_NULLS121 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#RETURNS_SMART_NULLS122 * }123 */124 /**125 * {@see Mockito126 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#14127 * }128 */129 @Test130 public void step_14() {131 List mock = mock(ArrayList.class, Mockito.RETURNS_SMART_NULLS);132 List mockTwo = mock(List.class, new Answer() {133 @Override134 public Object answer(InvocationOnMock invocation) throws Throwable {135 return false;136 }137 });138 System.out.println( mockTwo.add("haha"));139 }140 /*141 * Capturing arguments for further assertions (Since 1.8.0)142 * è¿ä¸ªåè½ï¼å¯ä»¥å¸®å©ä½ æ£éªç¸åºçåæ°çæ£ç¡®æ§143 * è¦åï¼å¿
须记ä½çæ¯ä½¿ç¨ArgumentCaptor åè½åºè¯¥æ¯æ£éªèä¸æ¯ç¨æ¥æ¿ä»£é»è®¤å¼ã144 * å¦æ使ç¨ArgumentCaptor å°åå°ä»£ç çå¯è¯»æ§ï¼å 为æè·æ¯å¨assertä¹å¤å建ï¼145 * ï¼ä¾å¦å¨aka verify æè
âthenâï¼146 * å®åæ¶åå°äºå®ä½ç¼ºé·ï¼å 为å¦æstubbedæ¹æ³æ²¡æ被è°ç¨ï¼é£ä¹å°ä¸ä¼æåæ°è¢«æè·147 * ArgumentCaptor æ´éç¨äºä»¥ä¸æ
å½¢ï¼148 * 1ãèªå®ä¹argument matcherä¸å¤ªå¯è½è¢«éç¨149 * 2ãä½ åªéè¦éªè¯å½æ°åæ°çåªå°±å¯ä»¥å®ææ ¡éª150 * {@see ArgumentMatcher151 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/ArgumentMatcher.html152 * }153 */154 /**155 * {@see Mockito156 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#15157 * }158 */159 @Test160 public void step_15() {161 ArrayList mock = mock(ArrayList.class);162 mock.add("John");163 ArgumentCaptor<List> argument = ArgumentCaptor.forClass(ArrayList.class);164 verify(mock).add(argument.capture());165 Assert.assertEquals("John", argument.getValue());166 }167 /*168 * Real partial mocks (Since 1.8.0)169 * å¨é¨åæ
åµä¸partial mocksæ¯é常æç¨ç170 * spy()ä¸spy(Object)æ¹æ³å¹¶æ²¡æ产çæ£å¸¸çpartial mocksï¼å
·ä½ä¿¡æ¯è¯·é
读171 * {@see172 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#13173 * }174 * éè¦æ³¨æçæ¯ï¼175 * æ好å¨æµè¯ç¬¬ä¸æ¹æ¥å£ï¼ä»¥åéç代ç çæ¶å使ç¨spy176 * ä¸è¦å¨æ°è®¾è®¡ç代ç ãå¯ä»¥æµè¯ç代ç ï¼ä»¥åè¯å¥½è®¾è®¡ç代ç ä¸ä½¿ç¨spy177 *178 */179 /**180 * {@see Mockito181 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#16182 * }183 */184 @Test185 public void step_16() {186 //you can create partial mock with spy() method:187 List list = spy(new LinkedList());188 //you can enable partial mock capabilities selectively on mocks:189 ArrayList mock = mock(ArrayList.class);190 //Be sure the real implementation is 'safe'.191 //If real implementation throws exceptions or depends on specific state of the object then you're in trouble.192 when(mock.add("haha")).thenCallRealMethod();193 }194 /*195 * Resetting mocks (Since 1.8.0)196 * "Please keep us small & focused on single behavior".197 * æ¯æ们åºå½éµå¾ªçè§åï¼å æ¤æ们é常并ä¸éè¦ä½¿ç¨resetï¼é¤éå¨ä¸ä¸ªåé¿çãè¶
éçæµè¯ä¸ä½¿ç¨ã198 * å®æ¹æ·»å restæ¹æ³çå¯ä¸åå å°±æ¯å¯ä»¥ä½¿ç¨å®¹å¨æ³¨å
¥ç模æå¨ã199 * {@see FAQ200 * https://github.com/mockito/mockito/wiki/FAQ201 * }202 * åè¯ä½ èªå·±ï¼203 * å¦ææ¯ä½¿ç¨resetæ¹æ³ï¼é£ä¹ä½ å¯è½åå¾å¤ªå¤äº204 */205 /**206 * {@see Mockito207 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#17208 * }209 */210 @Test211 public void step_17() {212 List mock = mock(List.class);213 when(mock.size()).thenReturn(10);214 mock.add(1);215 reset(mock);216 //at this point the mock forgot any interactions & stubbing217 }218 /*219 * Troubleshooting & validating framework usage220 * {@see FAQ221 * https://github.com/mockito/mockito/wiki/FAQ222 * }223 * æè
å¯ä»¥åè224 * http://groups.google.com/group/mockito225 */226 /**227 * {@see Mockito228 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#18229 * }230 */231 @Test232 public void step_18() {233 }234 /*235 * Aliases for behavior driven development (Since 1.8.0)236 * Behavior Driven Development (åºäºè¡ä¸ºé©±å¨çå¼å)å¨æ§è¡æµè¯æ¶ï¼å¯ä»¥ä½¿ç¨237 * //given //when //thençæ¹æ³ä½ä¸ºä½ æµè¯æ¹æ³çä¸é¨åã238 * {@see Behavior Driven Development (BDD)239 * http://en.wikipedia.org/wiki/Behavior_Driven_Development240 * }241 * é®é¢æ¯å½åstubbing apiä¸whenåçè§èä½ç¨ï¼æ²¡æå¾å¥½å°éæ//given//when//then注éã242 * è¿æ¯å 为å®å±äºgivenæµè¯å
容çstubbingï¼å¹¶ä¸å±äºwhenæµè¯å
容çsutbbing243 * å æ¤ï¼å æ¤ï¼BDDMockitoç±»å¼å
¥ä¸ä¸ªå«åï¼244 * 以便使ç¨BDDMockito.givenï¼Objectï¼æ¹æ³è¿è¡stubæ¹æ³è°ç¨ã245 * ç°å¨å®ççå¾å¥½å°ä¸BDDæ ·å¼æµè¯çç»å®ç»ä»¶éæï¼246 */247 /**248 * {@see Mockito249 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#19250 * }251 */252 @Test253 public void step_19() {254 ArrayList mock = mock(ArrayList.class);255 BDDMockito.given(mock.add("Test")).willReturn(false);256 System.out.println("mock.add(\"Test\") = " + mock.add("Test"));257 verify(mock).add("Test");258 }259 /*260 * Serializable mocks (Since 1.8.1)261 * Mockså¯ä»¥è¢«åä½ä¸ºå¯åºåå对象ãæäºè¿ä¸ªåè½ï¼ä½ å¯ä»¥å¨ä¸ä¸ªéè¦ä¾èµçå°æ¹ä½¿ç¨ä¸ä¸ªæ¨¡ææ¥è¿è¡åºååã262 * è¦åï¼è¿ä¸ªåè½åºè¯¥å¨åå
æµè¯ä¸å¾å°ç¨å°ã263 * 对äºå
·æä¸å¯é çå¤é¨ä¾èµæ§çBDDè§èçç¹å®ç¨ä¾ï¼å®æ½äºè¯¥è¡ä¸ºã264 * è¿æ¯å¨ä¸ä¸ªWebç¯å¢ä¸ï¼æ¥èªå¤é¨ä¾èµå
³ç³»ç对象被åºåå以å¨å±ä¹é´ä¼ éã265 */266 /**267 * {@see Mockito268 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#269 * }270 */271 @Test272 public void step_20() {273 List serializableMock = mock(List.class, withSettings().serializable());274 //å建ä¸ä¸ªçæ£ç对象spy serializable æ¯ä¸ä¸ªéè¦æ´å¤çåªåï¼275 //å 为spy(object)æ¹æ³æ²¡ææ¥åMockSettingsçéè½½çæ¬ï¼å«æ
å¿ï¼å ä¹ä¸ä¼ä½¿ç¨å®ã276 List<Object> list = new ArrayList<Object>();277 List<Object> spy = mock(ArrayList.class, withSettings()278 .spiedInstance(list)279 .defaultAnswer(CALLS_REAL_METHODS)280 .serializable());281 }282}...
Source:OfficalTest_Part_3.java
1package com.joke.mock.offical_mock;2import org.junit.Test;3import org.mockito.InOrder;4import java.util.ArrayList;5import static org.mockito.Mockito.ignoreStubs;6import static org.mockito.Mockito.inOrder;7import static org.mockito.Mockito.mock;8import static org.mockito.Mockito.verify;9import static org.mockito.Mockito.verifyNoMoreInteractions;10import static org.mockito.Mockito.when;11public class OfficalTest_Part_3 {12 /*13 * New annotations: @Captor, @Spy, @InjectMocks (Since 1.8.3)14 * @Captor simplifies creation of ArgumentCaptor - useful when the argument to capture is a nasty generic class and you want to avoid compiler warnings15 * @Spy - you can use it instead spy(Object).16 * @InjectMocks - injects mock or spy fields into tested object automatically.17 * éè¦æ³¨æçæ¯InjectMockså¯ä»¥ä¸@Spyè¿è¡ç»å使ç¨ãè¿å°±æå³çï¼Mockitoå°ä¼æ³¨å
¥mockså° partial mock18 * ç¨ä»¥è¿è¡æµè¯ãè½ç¶æ´å çå¤æï¼ä½æ¯å´åä¸ä¸ªå¾å¥½çåå å¯ä»¥è®©ä½ 使ç¨å®ï¼é£å°±æ¯å®å¯ä»¥ä½ä¸ºä½ 使ç¨partial mock19 * çæåçæ段ã20 * è¿äºææç注解ï¼åªå¨ MockitoAnnotations.initMocks(Object)ä¸å¤çï¼å°±åä½ ä½¿ç¨@Mock注解æ¶ï¼ä½ å¯ä»¥ä½¿ç¨21 * å
ç½®çMockitoJUnitRunner or rule: MockitoRule.22 */23 /**24 * {@see Mockito25 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#2126 * }27 */28 @Test29 public void step_21() {30 }31 /*32 * Verification with timeout (Since 1.8.5)33 * å
è®¸æ ¡éªè¶
æ¶ï¼å®å°ä¼å¯¼è´çå¾
ä¸ä¸ªç¹æ®çæ¶é´æ®µï¼ä»èææçäºæ
åçï¼èä¸æ¯ç«å³åçã34 * å¨æµè¯å¹¶åçæ¶åï¼å®å°å¯è½å¾æç¨ã35 * å®åºè¯¥å¾å°è¢«ä½¿ç¨å°-å¨æ¾å°ä¸ä¸ªæ´å¥½çæµè¯å¤çº¿ç¨ç³»ç»çæ¹æ³ã36 */37 /**38 * {@see Mockito39 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#2240 * }41 */42 @Test43 public void step_22() {44//45// //passes when someMethod() is called within given time span46// verify(mock, timeout(100)).someMethod();47// //above is an alias to:48// verify(mock, timeout(100).times(1)).someMethod();49//50// //passes when someMethod() is called *exactly* 2 times within given time span51// verify(mock, timeout(100).times(2)).someMethod();52//53// //passes when someMethod() is called *at least* 2 times within given time span54// verify(mock, timeout(100).atLeast(2)).someMethod();55//56// //verifies someMethod() within given time span using given verification mode57// //useful only if you have your own custom verification modes.58// verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod();59 }60 /*61 * Automatic instantiation of @Spies, @InjectMocks and constructor injection goodness (Since 1.9.0)62 * æ们éè¿ç»å@Spiesï¼å°ä¼å®ä¾åã注å
¥å¨ä½¿ç¨@InjectMocksçæé å½æ°ãsetteræ¹æ³ãæè
å
¨å±åéä¸63 *64 * {@see65 * äºè§£ç¸åºçæ¹æ³è°ç¨66 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/MockitoAnnotations.html#initMocks(java.lang.Object)67 * äºè§£JUnitRunnerè§å68 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/junit/MockitoJUnitRunner.html69 * äºè§£MockitoRule70 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/junit/MockitoRule.html71 * }72 * {@see InjectMocks å¯ä»¥äºè§£æ´å¤ç注å
¥çè§åï¼ä»¥åéå¶73 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/InjectMocks.html74 * }75 */76 /**77 * {@see Mockito78 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#2379 * }80 */81 @Test82 public void step_23() {83 }84 /*85 * One-liner stubs (Since 1.9.0)86 * æ们å¯ä»¥å¯ç¨ä¸è¡ä»£ç æ¥å建ç¸åºçmock对象ä¿è¯ç®æ´æ§ï¼ä¾å¦ä¸é¢çä¾å87 * public class CarTest {88 * Car boringStubbedCar = when(mock(Car.class).shiftGear()).thenThrow(EngineNotStarted.class).getMock();89 * @Test public void should... {}90 * }91 */92 /**93 * {@see Mockito94 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#2495 * }96 */97 @Test98 public void step_24() {99 ArrayList test = when(mock(ArrayList.class).add("Test")).thenThrow(new RuntimeException()).getMock();100 test.add("haha"); //æ£å¸¸è¿è¡101 test.add("Test"); //æåºå¼å¸¸102 }103 /*104 * Verification ignoring stubs (Since 1.9.0)105 * verifyNoMoreInteractions() æè
verification inOrder() å¯ä»¥å¸®å©æ们åå°ç¸åºçåä½éªè¯106 * è¦åï¼107 * éè¦æ³¨æçæ¯ignoreStubs() å°ä¼å¯¼è´è¿åº¦ç使ç¨verifyNoMoreInteractions(ignoreStubs(...))æ¹æ³108 * æ们并ä¸åºè¯¥å¨æ¯æ¬¡testæµè¯çæ¶åé½è°ç¨è¯¥verifyæ¹æ³ï¼å 为å®åªæ¯å¨æµè¯å·¥å
·ä¸ä½ä¸ºä¸ä¸ªç®åçãæ¹ä¾¿çæè¨109 * åºå½å¨é£äºéè¦ä½¿ç¨è¯¥æ¹æ³çæ¶åå使ç¨ã110 * {@see111 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#verifyNoMoreInteractions(java.lang.Object...)112 * https://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/113 * }114 */115 /**116 * {@see Mockito117 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#118 * }119 */120 @Test121 public void step_25() {122 ArrayList mock = mock(ArrayList.class);123 ArrayList mockTwo = mock(ArrayList.class);124 mock.clear();125 mockTwo.clear();126 verify(mock).clear();127 verify(mockTwo).clear();128 //ignores all stubbed methods:129 verifyNoMoreInteractions(ignoreStubs(mock, mockTwo));130 //creates InOrder that will ignore stubbed131 InOrder inOrder = inOrder(ignoreStubs(mock, mockTwo));132 inOrder.verify(mock).clear();133 inOrder.verify(mockTwo).clear();134 inOrder.verifyNoMoreInteractions();135 }136 /*137 * Mocking details (Improved in 2.2.x)138 * å¯ä»¥å¸®å©æ们è·åmock对象æè
spy对象çä¸äºå
·ä½çç»è139 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/MockingDetails.html140 */141 /**142 * {@see Mockito143 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#26144 * }145 */146 @Test147 public void step_26() {148// //To identify whether a particular object is a mock or a spy:149// Mockito.mockingDetails(someObject).isMock();150// Mockito.mockingDetails(someObject).isSpy();151// //Getting details like type to mock or default answer:152// MockingDetails details = mockingDetails(mock);153// details.getMockCreationSettings().getTypeToMock();154// details.getMockCreationSettings().getDefaultAnswer();155// //Getting interactions and stubbings of the mock:156// MockingDetails details = mockingDetails(mock);157// details.getInteractions();158// details.getStubbings();159// //Printing all interactions (including stubbing, unused stubs)160// System.out.println(mockingDetails(mock).printInvocations());161 }162 /*163 * Delegate calls to real instance (Since 1.9.5)164 * å©ç¨spiesæè
é¨å模æç对象å¾é¾ä½¿ç¨ä¸è¬çspyApiæ¥è¿è¡mockæè
spyãèä»1.10.11å¼å§ï¼è¿ç§å§æçæ¹æ³165 * å¯è½ä¸mockç¸åï¼ä¹å¯è½ä¸ä¹ä¸ç¸åãå¦æç±»åä¸ç¸åï¼é£ä¹å¨ä»£è¡¨çç±»åä¸æ¾å°ä¸ä¸ªå¹é
çæ¹æ³ï¼å¦åå°æåºå¼å¸¸166 * 以ä¸æ¯å¯è½ç¨å°è¿ç§åè½çæ
å½¢ï¼167 * Final classes but with an interface168 * Already custom proxied object169 * Special objects with a finalize method, i.e. to avoid executing it 2 times170 * ä¸é常çspy对象çä¸åä¹å¤å¨äº171 * 1ãé常çspy对象((spy(Object))ä»spiedçå®ä¾ä¸å
å«äºææçç¶æï¼å¹¶ä¸è¿äºæ¹æ³é½å¯ä»¥å¨spy对象ä¸å¼ç¨ã172 * è¿ä¸ªspiedçå®ä¾åªæ¯è¢«å½åï¼ä»å·²ç»å建çmock对象ä¸å¤å¶ææçç¶æçä¸ä¸ªå¯¹è±¡ãå¦æä½ å¨ä¸ä¸ªé常çspy对象173 * ä¸è°ç¨ä¸äºæ¹æ³ï¼å¹¶ä¸å®ä¼å¨è¿ä¸ªspy对象åè°ç¨å
¶ä»æ¹æ³ãå æ¤ï¼è¿äºè°ç¨å°ä¼è¢«è®°å½ä¸æ¥ç¨äºéªè¯ï¼å¹¶ä¸ä»ä»¬å¯174 * 以ææçä¿®æ¹ç¸åºçåæ ¹æ°æ®(stubbed)175 * 2ãmock对象代表çä¸ä¸ªå¯ä»¥æ¥æ¶æææ¹æ³çç®åå§æç对象ãè¿ä¸ªå§æå¯ä»¥å¨ä»»ä½æ¶åä¸è°ç¨å®çæææ¹æ³ã176 * å¦æä½ å¨ä¸ä¸ªmock对象ä¸è°ç¨ä¸ä¸ªæ¹æ³ï¼å¹¶ä¸å®å
é¨å¨è¿ä¸ªmock对象ä¸è°ç¨äºå
¶ä»çæ¹æ³ï¼é£ä¹è¿äºè°ç¨å°ä¸ä¼177 * è®°å½ä¸æ¥ç¨ä»¥éªè¯ï¼åæ ¹æ°æ®(stubbing)ä¹æ²¡æ对ä»ä»¬æä»»ä½å½±åãMockç¸å¯¹äºä¸ä¸ªé常çspy对象æ¥è¯´ï¼æ²¡æ178 * é£ä¹ç强大ï¼ä½æ¯å®å¯ä»¥é常æç¨çï¼å¨é£äºspy对象ä¸è½è¢«å建çæ¶å179 *180 */181 /**182 * {@see Mockito183 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#27184 * }185 */186 @Test187 public void step_27() {188 }189 /*190 * MockMaker API (Since 1.9.5)191 * ç±äºè°·æå®åä¸é对äºè®¾å¤ä»¥åè¡¥ä¸çéæ±ï¼Mockitoç°å¨æä¾äºä¸ä¸ªæ©å±ç¹ï¼å»æ¿ä»£ä»£ççæå¼æ192 * é»è®¤æ
åµä¸ï¼Mockitoä½¿ç¨ byte-buddyæ¥å建å¨æç代ç193 * {byte-buddy194 * https://github.com/raphw/byte-buddy195 * }196 * è¿ä¸ªæ©å±ç¹æ¯é对äºé£äºéè¦æ©å±Mockitoçé«çº§ç¨æ·ãç°å¨å¯ä»¥å©ç¨dexMatcheræ¥å¸®å©è¿è¡ä¸äº197 * Androidæ¹é¢çMockitoæµè¯198 * æ´å¤çå
容å¯ä»¥åèMockMarker199 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/plugins/MockMaker.html200 *201 */202 /**203 * {@see Mockito204 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#28205 * }206 */207 @Test208 public void step_28() {209 }210 /*211 * BDD style verification (Since 1.10.0)212 * Enables Behavior Driven Development (BDD) style verification by213 * starting verification with the BDD then keyword.214 * å¯ä»¥åè以ä¸çè¿æ¥ï¼è·åæ´å¤çå
容215 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/BDDMockito.html#then(T)216 */217 /**218 * {@see Mockito219 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#29220 * }221 */222 @Test223 public void step_29() {224 }225 /*226 * Spying or mocking abstract classes (Since 1.10.12, further enhanced in 2.7.13 and 2.7.14)227 * å¨æ¨¡ææ½è±¡ç±»çæ¶åï¼è¿ä¸ªåè½é常çæç¨ï¼å 为å®å¯ä»¥è®©ä½ ä¸åéè¦æä¾ä¸ä¸ªæ½è±¡ç±»çå®ä¾228 * ç®ååªæè¾å°åæ°ççæ¹é æ¹æ³çæ½è±¡ç±»å¯ä»¥æ¯æ229 */230 /**231 * {@see Mockito232 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#30233 * }234 */235 @Test236 public void step_30() {237// //convenience API, new overloaded spy() method:238// SomeAbstract spy = spy(SomeAbstract.class);239//240// //Mocking abstract methods, spying default methods of an interface (only avilable since 2.7.13)241// Function function = spy(Function.class);242//243// //Robust API, via settings builder:244// OtherAbstract spy = mock(OtherAbstract.class, withSettings()245// .useConstructor().defaultAnswer(CALLS_REAL_METHODS));246//247// //Mocking an abstract class with constructor arguments (only available since 2.7.14)248// SomeAbstract spy = mock(SomeAbstract.class, withSettings()249// .useConstructor("arg1", 123).defaultAnswer(CALLS_REAL_METHODS));250//251// //Mocking a non-static inner abstract class:252// InnerAbstract spy = mock(InnerAbstract.class, withSettings()253// .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));254 }255}...
Source:OfficalTest_Part_4.java
1package com.joke.mock.offical_mock;2import org.junit.Test;3import java.util.ArrayList;4import static org.mockito.Mockito.description;5import static org.mockito.Mockito.mock;6import static org.mockito.Mockito.times;7import static org.mockito.Mockito.verify;8public class OfficalTest_Part_4 {9 /*10 * Mockito mocks can be serialized / deserialized across classloaders (Since 1.10.0)11 * Mockitoå®ç°äºä»classloaderä¸å¼å
¥åºååã就好åä»»ä½å¯¹è±¡æ¥èªäºç³»ååä¹ä¸ï¼å¨mockå±æ¬¡ä¸çææ12 * ç±»åé½å¿
é¡»åºååï¼å¹¶ä¸å
å«answersï¼13 * è¿å¯ä»¥åè以ä¸å
容14 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/MockSettings.html#serializable(org.mockito.mock.SerializableMode)15 */16 /**17 * {@see Mockito18 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#3119 * }20 */21 @Test22 public void step_31() {23// // use regular serialization24// mock(Book.class, withSettings().serializable());25//26// // use serialization across classloaders27// mock(Book.class, withSettings().serializable(ACROSS_CLASSLOADERS));28 }29 /*30 * Better generic support with deep stubs (Since 1.10.0)31 * å¨ç±»ä¸å¦ææ³åä¿¡æ¯è¢«å¼å
¥ï¼è¿å°±æå³çç±»å¯ä»¥è¿æ ·è¢«ä½¿ç¨è没æmockè¡ä¸ºã32 *33 * 注æï¼34 * å¨å¤§å¤æ°æ
åµä¸ï¼mockè¿åmock对象æ¯é误çã35 */36 /**37 * {@see Mockito38 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#3239 * }40 */41 @Test42 public void step_32() {43//44// class Lines extends List<Line> {45// // ...46// }47//48// lines = mock(Lines.class, RETURNS_DEEP_STUBS);49//50// // Now Mockito understand this is not an Object but a Line51// Line line = lines.iterator().next();52 }53 /*54 * Mockito JUnit rule (Since 1.10.17)55 * å¨åå§å注解ä¸æ¯å¦@Mock @Spy @InjectMocksæ两ç§æ段ä¸æ¹æ³56 * 1ã使ç¨@RunWith(MockitoJUnitRunner.class)注解JUnitæµè¯ç±»57 * 2ãå¨ä½¿ç¨@Before注解çæ¹æ³ä¸ä½¿ç¨MockitoAnnotations.initMocks(Object)58 * Mockito.rule()59 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/junit/MockitoJUnit.html#rule()60 */61 /**62 * {@see Mockito63 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#64 * }65 */66 @Test67 public void step_33() {68// @RunWith(YetAnotherRunner.class)69// public class TheTest {70// @Rule public MockitoRule mockito = MockitoJUnit.rule();71// // ...72// }73 }74 /*75 * Switch on or off plugins (Since 1.10.15)76 * ä¸ä¸ªåµååè½ä½¿å®å¨mockitoçæ¹å¼ï¼å°å
许åæ¢mockitoæ件ã77 * PluginSwitch78 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/plugins/PluginSwitch.html79 */80 /**81 * {@see Mockito82 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#83 * }84 */85 @Test86 public void step_34() {87 }88 /*89 * Custom verification failure message (Since 2.1.0)90 * å¦ææ ¡éªå¤±è´¥çè¯ï¼å¯ä»¥èªå®ä¹çæ示信æ¯ã91 */92 /**93 * {@see Mockito94 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#3595 * }96 */97 @Test98 public void step_35() {99 ArrayList mock = mock(ArrayList.class);100 // will print a custom message on verification failure101 verify(mock, description("This will print on failure")).clear();102 // will work with any verification mode103 verify(mock, times(2).description("someMethod should be called twice")).size();104 }105 /*106 * Java 8 Lambda Matcher Support (Since 2.1.0)107 *108 */109 /**110 * {@see Mockito111 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#36112 * }113 */114 @Test115 public void step_36() {116//117// // verify a list only had strings of a certain length added to it118// // note - this will only compile under Java 8119// verify(list, times(2)).add(argThat(string -> string.length() < 5));120//121// // Java 7 equivalent - not as neat122// verify(list, times(2)).add(argThat(new ArgumentMatcher(){123// public boolean matches(String arg) {124// return arg.length() < 5;125// }126// }));127//128// // more complex Java 8 example - where you can specify complex verification behaviour functionally129// verify(target, times(1)).receiveComplexObject(argThat(obj -> obj.getSubObject().get(0).equals("expected")));130//131// // this can also be used when defining the behaviour of a mock under different inputs132// // in this case if the input list was fewer than 3 items the mock returns null133// when(mock.someMethod(argThat(list -> list.size()<3))).willReturn(null);134 }135 /*136 *137 */138 /**139 * {@see Mockito140 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#37141 * }142 */143 @Test144 public void step_37() {145// // answer by returning 12 every time146// doAnswer(invocation -> 12).when(mock).doSomething();147//148// // answer by using one of the parameters - converting into the right149// // type as your go - in this case, returning the length of the second string parameter150// // as the answer. This gets long-winded quickly, with casting of parameters.151// doAnswer(invocation -> ((String)invocation.getArgument(1)).length())152// .when(mock).doSomething(anyString(), anyString(), anyString());153//154// // Example interface to be mocked has a function like:155// void execute(String operand, Callback callback);156//157// // the example callback has a function and the class under test158// // will depend on the callback being invoked159// void receive(String item);160//161// // Java 8 - style 1162// doAnswer(AdditionalAnswers.answerVoid((operand, callback) -> callback.receive("dummy"))163// .when(mock).execute(anyString(), any(Callback.class));164//165// // Java 8 - style 2 - assuming static import of AdditionalAnswers166// doAnswer(answerVoid((String operand, Callback callback) -> callback.receive("dummy"))167// .when(mock).execute(anyString(), any(Callback.class));168//169// // Java 8 - style 3 - where mocking function to is a static member of test class170// private static void dummyCallbackImpl(String operation, Callback callback) {171// callback.receive("dummy");172// }173//174// doAnswer(answerVoid(TestClass::dummyCallbackImpl)175// .when(mock).execute(anyString(), any(Callback.class));176//177// // Java 7178// doAnswer(answerVoid(new VoidAnswer2() {179// public void answer(String operation, Callback callback) {180// callback.receive("dummy");181// }})).when(mock).execute(anyString(), any(Callback.class));182//183// // returning a value is possible with the answer() function184// // and the non-void version of the functional interfaces185// // so if the mock interface had a method like186// boolean isSameString(String input1, String input2);187//188// // this could be mocked189// // Java 8190// doAnswer(AdditionalAnswers.answer((input1, input2) -> input1.equals(input2))))191// .when(mock).execute(anyString(), anyString());192//193// // Java 7194// doAnswer(answer(new Answer2() {195// public String answer(String input1, String input2) {196// return input1 + input2;197// }})).when(mock).execute(anyString(), anyString());198 }199 /*200 * Meta data and generic type retention (Since 2.1.0)201 * Mockitoç°å¨ä¿çmockedæ¹æ³ä»¥åç±»åä¸ç注éä¿¡æ¯ï¼å°±åä½ä¸ºæ³åå±æ§æ°æ®ä¸æ ·ã202 * 以åï¼æ¨¡æç±»å没æä¿ç对类åç注éï¼é¤éå®ä»¬è¢«æ¾å¼å°ç»§æ¿ï¼å¹¶ä¸ä»æªå¨æ¹æ³ä¸ä¿ç注éã203 * å æ¤ï¼ç°å¨çæ¡ä»¶å¦ä¸ï¼204 * å½æ¶ç¨Java8æ¶ï¼Mockitoç°å¨ä¹ä¼ä¿çç±»å注解ï¼è¿æ¯é»è®¤è¡ä¸ºï¼å¦æ使ç¨å¦ä¸ä¸ªMockMakerå¯è½ä¸ä¼ä¿çã205 */206 /**207 * {@see Mockito208 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#38209 * }210 */211 @Test212 public void step_38() {213// @MyAnnotation214// class Foo {215// List<String> bar() { ... }216// }217//218// Class<?> mockType = mock(Foo.class).getClass();219// assert mockType.isAnnotationPresent(MyAnnotation.class);220// assert mockType.getDeclaredMethod("bar").getGenericReturnType() instanceof ParameterizedType;221 }222 /*223 * Mocking final types, enums and final methods (Since 2.1.0)224 */225 /**226 * {@see Mockito227 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#39228 * }229 */230 @Test231 public void step_39() {232 }233 /*234 *235 */236 /**237 * {@see Mockito238 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#239 * }240 */241 @Test242 public void step_40() {243 }244}...
Source:TestCachingKeyProvider.java
...20import org.apache.hadoop.conf.Configuration;21import org.apache.hadoop.crypto.key.kms.KMSClientProvider;22import org.junit.Assert;23import org.junit.Test;24import org.mockito.Mockito;25public class TestCachingKeyProvider {26 @Test27 public void testCurrentKey() throws Exception {28 KeyProvider.KeyVersion mockKey = Mockito.mock(KeyProvider.KeyVersion.class);29 KeyProvider mockProv = Mockito.mock(KeyProvider.class);30 Mockito.when(mockProv.getCurrentKey(Mockito.eq("k1"))).thenReturn(mockKey);31 Mockito.when(mockProv.getCurrentKey(Mockito.eq("k2"))).thenReturn(null);32 Mockito.when(mockProv.getConf()).thenReturn(new Configuration());33 KeyProvider cache = new CachingKeyProvider(mockProv, 100, 100);34 // asserting caching35 Assert.assertEquals(mockKey, cache.getCurrentKey("k1"));36 Mockito.verify(mockProv, Mockito.times(1)).getCurrentKey(Mockito.eq("k1"));37 Assert.assertEquals(mockKey, cache.getCurrentKey("k1"));38 Mockito.verify(mockProv, Mockito.times(1)).getCurrentKey(Mockito.eq("k1"));39 Thread.sleep(1200);40 Assert.assertEquals(mockKey, cache.getCurrentKey("k1"));41 Mockito.verify(mockProv, Mockito.times(2)).getCurrentKey(Mockito.eq("k1"));42 // asserting no caching when key is not known43 cache = new CachingKeyProvider(mockProv, 100, 100);44 Assert.assertEquals(null, cache.getCurrentKey("k2"));45 Mockito.verify(mockProv, Mockito.times(1)).getCurrentKey(Mockito.eq("k2"));46 Assert.assertEquals(null, cache.getCurrentKey("k2"));47 Mockito.verify(mockProv, Mockito.times(2)).getCurrentKey(Mockito.eq("k2"));48 }49 @Test50 public void testKeyVersion() throws Exception {51 KeyProvider.KeyVersion mockKey = Mockito.mock(KeyProvider.KeyVersion.class);52 KeyProvider mockProv = Mockito.mock(KeyProvider.class);53 Mockito.when(mockProv.getKeyVersion(Mockito.eq("k1@0")))54 .thenReturn(mockKey);55 Mockito.when(mockProv.getKeyVersion(Mockito.eq("k2@0"))).thenReturn(null);56 Mockito.when(mockProv.getConf()).thenReturn(new Configuration());57 KeyProvider cache = new CachingKeyProvider(mockProv, 100, 100);58 // asserting caching59 Assert.assertEquals(mockKey, cache.getKeyVersion("k1@0"));60 Mockito.verify(mockProv, Mockito.times(1))61 .getKeyVersion(Mockito.eq("k1@0"));62 Assert.assertEquals(mockKey, cache.getKeyVersion("k1@0"));63 Mockito.verify(mockProv, Mockito.times(1))64 .getKeyVersion(Mockito.eq("k1@0"));65 Thread.sleep(200);66 Assert.assertEquals(mockKey, cache.getKeyVersion("k1@0"));67 Mockito.verify(mockProv, Mockito.times(2))68 .getKeyVersion(Mockito.eq("k1@0"));69 // asserting no caching when key is not known70 cache = new CachingKeyProvider(mockProv, 100, 100);71 Assert.assertEquals(null, cache.getKeyVersion("k2@0"));72 Mockito.verify(mockProv, Mockito.times(1))73 .getKeyVersion(Mockito.eq("k2@0"));74 Assert.assertEquals(null, cache.getKeyVersion("k2@0"));75 Mockito.verify(mockProv, Mockito.times(2))76 .getKeyVersion(Mockito.eq("k2@0"));77 }78 @Test79 public void testMetadata() throws Exception {80 KeyProvider.Metadata mockMeta = Mockito.mock(KeyProvider.Metadata.class);81 KeyProvider mockProv = Mockito.mock(KeyProvider.class);82 Mockito.when(mockProv.getMetadata(Mockito.eq("k1"))).thenReturn(mockMeta);83 Mockito.when(mockProv.getMetadata(Mockito.eq("k2"))).thenReturn(null);84 Mockito.when(mockProv.getConf()).thenReturn(new Configuration());85 KeyProvider cache = new CachingKeyProvider(mockProv, 100, 100);86 // asserting caching87 Assert.assertEquals(mockMeta, cache.getMetadata("k1"));88 Mockito.verify(mockProv, Mockito.times(1)).getMetadata(Mockito.eq("k1"));89 Assert.assertEquals(mockMeta, cache.getMetadata("k1"));90 Mockito.verify(mockProv, Mockito.times(1)).getMetadata(Mockito.eq("k1"));91 Thread.sleep(200);92 Assert.assertEquals(mockMeta, cache.getMetadata("k1"));93 Mockito.verify(mockProv, Mockito.times(2)).getMetadata(Mockito.eq("k1"));94 // asserting no caching when key is not known95 cache = new CachingKeyProvider(mockProv, 100, 100);96 Assert.assertEquals(null, cache.getMetadata("k2"));97 Mockito.verify(mockProv, Mockito.times(1)).getMetadata(Mockito.eq("k2"));98 Assert.assertEquals(null, cache.getMetadata("k2"));99 Mockito.verify(mockProv, Mockito.times(2)).getMetadata(Mockito.eq("k2"));100 }101 @Test102 public void testRollNewVersion() throws Exception {103 KeyProvider.KeyVersion mockKey = Mockito.mock(KeyProvider.KeyVersion.class);104 KeyProvider mockProv = Mockito.mock(KeyProvider.class);105 Mockito.when(mockProv.getCurrentKey(Mockito.eq("k1"))).thenReturn(mockKey);106 Mockito.when(mockProv.getConf()).thenReturn(new Configuration());107 KeyProvider cache = new CachingKeyProvider(mockProv, 100, 100);108 Assert.assertEquals(mockKey, cache.getCurrentKey("k1"));109 Mockito.verify(mockProv, Mockito.times(1)).getCurrentKey(Mockito.eq("k1"));110 cache.rollNewVersion("k1");111 // asserting the cache is purged112 Assert.assertEquals(mockKey, cache.getCurrentKey("k1"));113 Mockito.verify(mockProv, Mockito.times(2)).getCurrentKey(Mockito.eq("k1"));114 cache.rollNewVersion("k1", new byte[0]);115 Assert.assertEquals(mockKey, cache.getCurrentKey("k1"));116 Mockito.verify(mockProv, Mockito.times(3)).getCurrentKey(Mockito.eq("k1"));117 }118 @Test119 public void testDeleteKey() throws Exception {120 KeyProvider.KeyVersion mockKey = Mockito.mock(KeyProvider.KeyVersion.class);121 KeyProvider mockProv = Mockito.mock(KeyProvider.class);122 Mockito.when(mockProv.getCurrentKey(Mockito.eq("k1"))).thenReturn(mockKey);123 Mockito.when(mockProv.getKeyVersion(Mockito.eq("k1@0")))124 .thenReturn(mockKey);125 Mockito.when(mockProv.getMetadata(Mockito.eq("k1"))).thenReturn(126 new KMSClientProvider.KMSMetadata("c", 0, "l", null, new Date(), 1));127 Mockito.when(mockProv.getConf()).thenReturn(new Configuration());128 KeyProvider cache = new CachingKeyProvider(mockProv, 100, 100);129 Assert.assertEquals(mockKey, cache.getCurrentKey("k1"));130 Mockito.verify(mockProv, Mockito.times(1)).getCurrentKey(Mockito.eq("k1"));131 Assert.assertEquals(mockKey, cache.getKeyVersion("k1@0"));132 Mockito.verify(mockProv, Mockito.times(1))133 .getKeyVersion(Mockito.eq("k1@0"));134 cache.deleteKey("k1");135 // asserting the cache is purged136 Assert.assertEquals(mockKey, cache.getCurrentKey("k1"));137 Mockito.verify(mockProv, Mockito.times(2)).getCurrentKey(Mockito.eq("k1"));138 Assert.assertEquals(mockKey, cache.getKeyVersion("k1@0"));139 Mockito.verify(mockProv, Mockito.times(2))140 .getKeyVersion(Mockito.eq("k1@0"));141 }142}...
Source:PartnerBookmarksReaderTest.java
...6import org.junit.Before;7import org.junit.Rule;8import org.junit.Test;9import org.junit.runner.RunWith;10import org.mockito.ArgumentCaptor;11import org.mockito.Captor;12import org.mockito.Mock;13import org.mockito.Mockito;14import org.mockito.MockitoAnnotations;15import org.robolectric.annotation.Config;16import org.chromium.base.test.BaseRobolectricTestRunner;17import org.chromium.base.test.util.JniMocker;18import org.chromium.chrome.browser.partnercustomizations.PartnerBrowserCustomizations;19/**20 * Unit tests for PartnerBookmarksReader.21 */22@RunWith(BaseRobolectricTestRunner.class)23@Config(manifest = Config.NONE)24public class PartnerBookmarksReaderTest {25 @Rule26 public JniMocker mocker = new JniMocker();27 @Mock28 Context mContextMock;29 @Mock30 PartnerBookmarksReader.Natives mJniMock;31 @Mock32 PartnerBrowserCustomizations mBrowserCustomizations;33 @Captor34 ArgumentCaptor<Runnable> mBrowserCustomizationsInitCallback;35 @Before36 public void setUp() {37 MockitoAnnotations.initMocks(this);38 mocker.mock(PartnerBookmarksReaderJni.TEST_HOOKS, mJniMock);39 Mockito.doNothing()40 .when(mBrowserCustomizations)41 .setOnInitializeAsyncFinished(mBrowserCustomizationsInitCallback.capture());42 }43 @Test44 public void partnerBrowserCustomizations_BookmarkEditingDisabled_AlreadyInitialized() {45 Mockito.when(mBrowserCustomizations.isInitialized()).thenReturn(true);46 @SuppressWarnings("unused")47 PartnerBookmarksReader reader =48 new PartnerBookmarksReader(mContextMock, mBrowserCustomizations);49 Mockito.verify(mBrowserCustomizations, Mockito.never()).initializeAsync(mContextMock);50 Mockito.when(mBrowserCustomizations.isBookmarksEditingDisabled()).thenReturn(true);51 mBrowserCustomizationsInitCallback.getValue().run();52 Mockito.verify(mJniMock).disablePartnerBookmarksEditing();...
Source:ControllerTest.java
...4import com.github.vitalibo.brickgame.core.ui.IconPanel;5import com.github.vitalibo.brickgame.game.Game;6import com.github.vitalibo.brickgame.game.Menu;7import lombok.experimental.Delegate;8import org.mockito.Mock;9import org.mockito.Mockito;10import org.mockito.MockitoAnnotations;11import org.mockito.Spy;12import org.testng.Assert;13import org.testng.annotations.BeforeMethod;14import org.testng.annotations.DataProvider;15import org.testng.annotations.Test;16import java.awt.event.KeyEvent;17import java.util.function.Consumer;18public class ControllerTest {19 @Mock20 private BrickGameFrame mockFrame;21 @Mock22 private IconPanel mockPause;23 @Mock24 private IconPanel mockSound;25 @Mock26 private BrickPanel mockBoard;27 @Mock28 private BrickPanel mockPreview;29 @Mock30 private KeyEvent mockKeyEvent;31 @Spy32 private Kernel spyKernel;33 private Controller spyController;34 @BeforeMethod35 public void setUp() {36 MockitoAnnotations.initMocks(this);37 Mockito.when(mockFrame.getPause()).thenReturn(mockPause);38 Mockito.when(mockFrame.getSound()).thenReturn(mockSound);39 Mockito.when(mockFrame.getBoard()).thenReturn(mockBoard);40 Mockito.when(mockFrame.getPreview()).thenReturn(mockPreview);41 spyController = Mockito.spy(new Controller(mockFrame, spyKernel));42 spyController.init(EmbeddedGame.class);43 }44 @DataProvider45 public Object[][] actions() {46 return new Object[][]{47 {KeyEvent.VK_UP, action(Controller::doUp)},48 {KeyEvent.VK_DOWN, action(Controller::doDown)},49 {KeyEvent.VK_LEFT, action(Controller::doLeft)},50 {KeyEvent.VK_RIGHT, action(Controller::doRight)},51 {KeyEvent.VK_SPACE, action(Controller::doRotate)}52 };53 }54 @Test(dataProvider = "actions")55 public void testDelegateKeyPressed(int keyEvent, Consumer<Controller> consumer) {56 Mockito.when(mockKeyEvent.getKeyCode()).thenReturn(keyEvent);57 spyController.keyPressed(mockKeyEvent);58 consumer.accept(Mockito.verify(spyController));59 }60 @Test(dataProvider = "actions")61 public void testNotDelegateKeyPressed(int keyEvent, Consumer<Controller> consumer) {62 Mockito.when(mockPause.get()).thenReturn(true);63 Mockito.when(mockKeyEvent.getKeyCode()).thenReturn(keyEvent);64 spyController.keyPressed(mockKeyEvent);65 consumer.accept(Mockito.verify(spyController, Mockito.never()));66 }67 @Test68 public void testChangeSound() {69 Mockito.when(mockKeyEvent.getKeyCode()).thenReturn(KeyEvent.VK_S);70 spyController.keyPressed(mockKeyEvent);71 Mockito.verify(mockSound).change();72 }73 @Test74 public void testChangePause() {75 Mockito.when(mockKeyEvent.getKeyCode()).thenReturn(KeyEvent.VK_P);76 Kernel.Job job = spyKernel.job(this, 100, o -> {77 });78 spyController.keyPressed(mockKeyEvent);79 boolean state = Mockito.verify(mockPause).change();80 Assert.assertEquals(job.isPause(), state);81 }82 @Test83 public void testReset() {84 Mockito.when(mockKeyEvent.getKeyCode()).thenReturn(KeyEvent.VK_R);85 Kernel.Job job = spyKernel.job(this, 100, o -> {86 });87 spyController.keyPressed(mockKeyEvent);88 Mockito.verify(spyController).init(Menu.class);89 Mockito.verify(spyController).unlock();90 Assert.assertTrue(job.isKilled());91 }92 private static Consumer<Controller> action(Consumer<Controller> action) {93 return action;94 }95 public static class EmbeddedGame extends Game {96 @Mock97 @Delegate98 private Game game;99 public EmbeddedGame(Context context) {100 super(context);101 MockitoAnnotations.initMocks(this);...
Source:MockitoTestExecutionListenerTests.java
...12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package org.springframework.boot.test.mock.mockito;17import java.io.InputStream;18import java.lang.reflect.Field;19import org.junit.Before;20import org.junit.Test;21import org.mockito.ArgumentCaptor;22import org.mockito.Captor;23import org.mockito.Mock;24import org.mockito.MockitoAnnotations;25import org.springframework.context.ApplicationContext;26import org.springframework.test.context.TestContext;27import static org.assertj.core.api.Assertions.assertThat;28import static org.mockito.BDDMockito.given;29import static org.mockito.Matchers.any;30import static org.mockito.Matchers.eq;31import static org.mockito.Mockito.mock;32import static org.mockito.Mockito.verify;33/**34 * Tests for {@link MockitoTestExecutionListener}.35 *36 * @author Phillip Webb37 */38public class MockitoTestExecutionListenerTests {39 private MockitoTestExecutionListener listener = new MockitoTestExecutionListener();40 @Mock41 private ApplicationContext applicationContext;42 @Mock43 private MockitoPostProcessor postProcessor;44 @Captor45 private ArgumentCaptor<Field> fieldCaptor;46 @Before47 public void setup() {48 MockitoAnnotations.initMocks(this);49 given(this.applicationContext.getBean(MockitoPostProcessor.class))50 .willReturn(this.postProcessor);51 }52 @Test53 public void prepareTestInstanceShouldInitMockitoAnnotations() throws Exception {54 WithMockitoAnnotations instance = new WithMockitoAnnotations();55 this.listener.prepareTestInstance(mockTestContext(instance));56 assertThat(instance.mock).isNotNull();57 assertThat(instance.captor).isNotNull();58 }59 @Test60 public void prepareTestInstanceShouldInjectMockBean() throws Exception {61 WithMockBean instance = new WithMockBean();62 this.listener.prepareTestInstance(mockTestContext(instance));63 verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance),64 (MockDefinition) any());65 assertThat(this.fieldCaptor.getValue().getName()).isEqualTo("mockBean");66 }67 @SuppressWarnings({ "unchecked", "rawtypes" })68 private TestContext mockTestContext(Object instance) {69 TestContext testContext = mock(TestContext.class);70 given(testContext.getTestInstance()).willReturn(instance);71 given(testContext.getTestClass()).willReturn((Class) instance.getClass());72 given(testContext.getApplicationContext()).willReturn(this.applicationContext);73 return testContext;74 }75 static class WithMockitoAnnotations {76 @Mock77 InputStream mock;78 @Captor79 ArgumentCaptor<InputStream> captor;80 }81 static class WithMockBean {82 @MockBean83 InputStream mockBean;84 }85}...
mock
Using AI Code Generation
1package org.example;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.mockito.InjectMocks;5import org.mockito.Mock;6import org.mockito.Mockito;7import org.mockito.junit.MockitoJUnitRunner;8import static org.junit.Assert.assertEquals;9import static org.mockito.Mockito.when;10@RunWith(MockitoJUnitRunner.class)11public class AppTest {12 App app;13 AppTest appTest;14 public void testApp() {15 when(app.add(10, 20)).thenReturn(30);16 assertEquals(30, appTest.add(10, 20));17 }18}19[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ mockito-mock-method ---20[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ mockito-mock-method ---21[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ mockito-mock-method ---22[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ mockito-mock-method ---23[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ mockito-mock-method ---
mock
Using AI Code Generation
1import org.mockito.Mockito;2import static org.mockito.Mockito.*;3import org.mockito.Matchers;4import org.mockito.ArgumentCaptor;5import org.mockito.invocation.InvocationOnMock;6import org.mockito.stubbing.Answer;7import org.mockito.verification.VerificationMode;8import org.mockito.verification.Verification
mock
Using AI Code Generation
1import org.mockito.Mockito;2public class 1 {3 public static void main(String[] args) {4 List mockedList = Mockito.mock(List.class);5 mockedList.add("one");6 mockedList.clear();7 Mockito.verify(mockedList).add("one");8 Mockito.verify(mockedList).clear();9 }10}
mock
Using AI Code Generation
1package com.ack.j2se.mockito;2import org.junit.Test;3import static org.junit.Assert.*;4import static org.mockito.Mockito.*;5public class MockitoTest {6 public void testMockito() {7 MyClass test = mock( MyClass.class );8 when( test.getUniqueId() ).thenReturn( 43 );9 assertEquals( test.testing( 12 ), 43 );10 test.someMethod();11 }12}13package com.ack.j2se.mockito;14public class MyClass {15 public int getUniqueId() {16 return 0;17 }18 public int testing( int i ) {19 return i * 2;20 }21 public void someMethod() {22 System.out.println( "someMethod" );23 }24}251. -> at com.ack.j2se.mockito.MockitoTest.testMockito(MockitoTest.java:24)262. -> at com.ack.j2se.mockito.MockitoTest.testMockito(MockitoTest.java:24)
mock
Using AI Code Generation
1public class 1 {2 public static void main(String[] args) {3 List mockList = mock(List.class);4 when(mockList.get(0)).thenReturn("first");5 System.out.println(mockList.get(0));6 System.out.println(mockList.get(1));7 }8}
mock
Using AI Code Generation
1package com.ack.j2se.mock;2import java.util.List;3import static org.mockito.Mockito.*;4public class MockingMockito {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 }12}13package com.ack.j2se.mock;14import java.util.List;15import static org.mockito.Mockito.*;16public class MockingMockito {17 public static void main( String[] args ) {18 List mockedList = mock( List.class );19 mockedList.add( "one" );20 mockedList.clear();21 verify( mockedList ).add( "one" );22 verify( mockedList ).clear();23 }24}25package com.ack.j2se.mock;26import java.util.List;27import static org.mockito.Mockito.*;28public class MockingMockito {29 public static void main( String[] args ) {30 List mockedList = mock( List.class );31 mockedList.add( "one" );32 mockedList.clear();33 verify( mockedList ).add( "one" );34 verify( mockedList ).clear();35 }36}37package com.ack.j2se.mock;38import java.util.List;39import static org.mockito.Mockito.*;40public class MockingMockito {41 public static void main( String[] args ) {42 List mockedList = mock( List.class );43 mockedList.add( "one" );44 mockedList.clear();45 verify( mockedList ).add( "one" );46 verify( mockedList ).clear();47 }48}
mock
Using AI Code Generation
1import static org.mockito.Mockito.*;2import static org.junit.Assert.*;3import org.junit.Test;4public class Test1 {5 public void test1() {6 Calculator mockCalc = mock(Calculator.class);7 when(mockCalc.add(10, 20)).thenReturn(30);8 assertEquals(mockCalc.add(10, 20), 30);9 }10}11import static org.mockito.Mockito.*;12import static org.junit.Assert.*;13import org.junit.Test;14public class Test2 {15 public void test2() {16 Calculator mockCalc = mock(Calculator.class);17 when(mockCalc.add(10, 20)).thenReturn(30);18 assertEquals(mockCalc.add(10, 20), 30);19 }20}21public class Calculator {22 public int add(int a, int b) {23 return a + b;24 }25}26BUILD SUCCESSFUL (total time: 0 seconds)27The following code shows the usage of the thenReturn() method of the stubber object:28when(mockCalc.add(10, 20)).thenReturn(30);29The following code shows the usage of the thenThrow() method of the stubber object:30when(mockCalc.add(10, 20)).thenThrow
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!!