Best Mockito code snippet using org.mockito.Mockito
Source:OfficalTest_Part_1.java
...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"));...
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//...
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:TabBrowserControlsConstraintsHelperTest.java
...8import org.junit.Test;9import org.junit.runner.RunWith;10import org.mockito.ArgumentCaptor;11import org.mockito.Mock;12import org.mockito.Mockito;13import org.mockito.MockitoAnnotations;14import org.robolectric.annotation.Config;15import org.chromium.base.UserDataHost;16import org.chromium.base.test.BaseRobolectricTestRunner;17import org.chromium.base.test.util.JniMocker;18import org.chromium.chrome.browser.ChromeActivity;19import org.chromium.components.browser_ui.util.BrowserControlsVisibilityDelegate;20import org.chromium.content_public.browser.WebContents;21import org.chromium.content_public.common.BrowserControlsState;22import org.chromium.ui.base.WindowAndroid;23import java.lang.ref.WeakReference;24/** Unit tests for {@link TabBrowserControlsConstraintsHelper}. */25@RunWith(BaseRobolectricTestRunner.class)26@Config(manifest = Config.NONE)27public class TabBrowserControlsConstraintsHelperTest {28 private final UserDataHost mUserDataHost = new UserDataHost();29 @Rule30 public JniMocker mocker = new JniMocker();31 @Mock32 TabImpl mTab;33 @Mock34 WebContents mWebContents;35 @Mock36 TabDelegateFactory mDelegateFactory;37 @Mock38 TabBrowserControlsConstraintsHelper.Natives mJniMock;39 private TabBrowserControlsConstraintsHelper mHelper;40 private TabObserver mRegisteredTabObserver;41 private TestVisibilityDelegate mVisibilityDelegate;42 @Before43 public void setUp() {44 MockitoAnnotations.initMocks(this);45 mocker.mock(TabBrowserControlsConstraintsHelperJni.TEST_HOOKS, mJniMock);46 Mockito.when(mTab.getUserDataHost()).thenReturn(mUserDataHost);47 Mockito.when(mTab.getDelegateFactory()).thenReturn(mDelegateFactory);48 Mockito.when(mTab.getWebContents()).thenReturn(mWebContents);49 mVisibilityDelegate = new TestVisibilityDelegate();50 Mockito.when(mDelegateFactory.createBrowserControlsVisibilityDelegate(Mockito.any()))51 .thenReturn(mVisibilityDelegate);52 }53 private void initHelper() {54 ArgumentCaptor<TabObserver> observerArg = ArgumentCaptor.forClass(TabObserver.class);55 TabBrowserControlsConstraintsHelper.createForTab(mTab);56 mHelper = TabBrowserControlsConstraintsHelper.get(mTab);57 Mockito.verify(mTab).addObserver(observerArg.capture());58 mRegisteredTabObserver = observerArg.getValue();59 }60 @Test61 public void testUpdateVisibilityDelegate_onInitialized() {62 initHelper();63 Mockito.verify(mDelegateFactory, Mockito.never())64 .createBrowserControlsVisibilityDelegate(mTab);65 mRegisteredTabObserver.onInitialized(mTab, null, null, 0);66 Mockito.verify(mDelegateFactory, Mockito.times(1))67 .createBrowserControlsVisibilityDelegate(mTab);68 verifyUpdateState(BrowserControlsState.BOTH);69 mVisibilityDelegate.set(BrowserControlsState.SHOWN);70 verifyUpdateState(BrowserControlsState.SHOWN);71 }72 @Test73 public void testUpdateVisibilityDelegate_TabAlreadyInitializedAndAttached() {74 Mockito.when(mTab.isInitialized()).thenReturn(true);75 WindowAndroid window = Mockito.mock(WindowAndroid.class);76 Mockito.when(mWebContents.getTopLevelNativeWindow()).thenReturn(window);77 ChromeActivity activity = Mockito.mock(ChromeActivity.class);78 WeakReference<Context> activityRef = new WeakReference<>(activity);79 Mockito.when(window.getContext()).thenReturn(activityRef);80 initHelper();81 Mockito.verify(mDelegateFactory, Mockito.times(1))82 .createBrowserControlsVisibilityDelegate(mTab);83 verifyUpdateState(BrowserControlsState.BOTH);84 mVisibilityDelegate.set(BrowserControlsState.SHOWN);85 verifyUpdateState(BrowserControlsState.SHOWN);86 }87 @Test88 public void testUpdateVisibilityDelegate_onAttachmentChanged() {89 initHelper();90 Mockito.verify(mDelegateFactory, Mockito.never())91 .createBrowserControlsVisibilityDelegate(mTab);92 mRegisteredTabObserver.onActivityAttachmentChanged(mTab, null);93 Mockito.verify(mDelegateFactory, Mockito.never())94 .createBrowserControlsVisibilityDelegate(mTab);95 WindowAndroid window = Mockito.mock(WindowAndroid.class);96 mRegisteredTabObserver.onActivityAttachmentChanged(mTab, window);97 Mockito.verify(mDelegateFactory, Mockito.times(1))98 .createBrowserControlsVisibilityDelegate(mTab);99 verifyUpdateState(BrowserControlsState.BOTH);100 mVisibilityDelegate.set(BrowserControlsState.SHOWN);101 verifyUpdateState(BrowserControlsState.SHOWN);102 }103 @Test104 public void testUpdateVisibilityDelegate_ChangeDelegates() {105 initHelper();106 Mockito.verify(mDelegateFactory, Mockito.never())107 .createBrowserControlsVisibilityDelegate(mTab);108 mRegisteredTabObserver.onInitialized(mTab, null, null, 0);109 Mockito.verify(mDelegateFactory).createBrowserControlsVisibilityDelegate(mTab);110 Mockito.verifyNoMoreInteractions(mDelegateFactory);111 verifyUpdateState(BrowserControlsState.BOTH);112 mVisibilityDelegate.set(BrowserControlsState.HIDDEN);113 verifyUpdateState(BrowserControlsState.HIDDEN, false);114 TabDelegateFactory newDelegateFactory = Mockito.mock(TabDelegateFactory.class);115 TestVisibilityDelegate newVisibilityDelegate = new TestVisibilityDelegate();116 Mockito.when(mTab.getDelegateFactory()).thenReturn(newDelegateFactory);117 Mockito.when(newDelegateFactory.createBrowserControlsVisibilityDelegate(Mockito.any()))118 .thenReturn(newVisibilityDelegate);119 WindowAndroid window = Mockito.mock(WindowAndroid.class);120 mRegisteredTabObserver.onActivityAttachmentChanged(mTab, window);121 Mockito.verify(newDelegateFactory).createBrowserControlsVisibilityDelegate(mTab);122 verifyUpdateState(BrowserControlsState.BOTH);123 mVisibilityDelegate.set(BrowserControlsState.SHOWN);124 Mockito.verify(mJniMock, Mockito.never())125 .updateState(Mockito.anyLong(), Mockito.any(), Mockito.any(), Mockito.anyInt(),126 Mockito.anyInt(), Mockito.anyBoolean());127 }128 @Test129 public void testWebContentsSwap() {130 initHelper();131 Mockito.verify(mDelegateFactory, Mockito.never())132 .createBrowserControlsVisibilityDelegate(mTab);133 mRegisteredTabObserver.onInitialized(mTab, null, null, 0);134 Mockito.verify(mDelegateFactory).createBrowserControlsVisibilityDelegate(mTab);135 Mockito.verifyNoMoreInteractions(mDelegateFactory);136 verifyUpdateState(BrowserControlsState.BOTH);137 mRegisteredTabObserver.onWebContentsSwapped(mTab, true, true);138 verifyUpdateState(BrowserControlsState.BOTH);139 }140 @Test141 public void testWebContentsSwap_whenShown() {142 initHelper();143 Mockito.verify(mDelegateFactory, Mockito.never())144 .createBrowserControlsVisibilityDelegate(mTab);145 mRegisteredTabObserver.onInitialized(mTab, null, null, 0);146 Mockito.verify(mDelegateFactory).createBrowserControlsVisibilityDelegate(mTab);147 Mockito.verifyNoMoreInteractions(mDelegateFactory);148 verifyUpdateState(BrowserControlsState.BOTH);149 mVisibilityDelegate.set(BrowserControlsState.SHOWN);150 verifyUpdateState(BrowserControlsState.SHOWN);151 mRegisteredTabObserver.onWebContentsSwapped(mTab, true, true);152 verifyUpdateState(BrowserControlsState.SHOWN, BrowserControlsState.SHOWN, false);153 }154 private void verifyUpdateState(@BrowserControlsState int constraints) {155 verifyUpdateState(constraints, BrowserControlsState.BOTH, true);156 }157 private void verifyUpdateState(@BrowserControlsState int constraints, boolean animate) {158 verifyUpdateState(constraints, BrowserControlsState.BOTH, animate);159 }160 private void verifyUpdateState(@BrowserControlsState int constraints,161 @BrowserControlsState int current, boolean animate) {162 Mockito.verify(mJniMock).updateState(Mockito.anyLong(), Mockito.same(mHelper),163 Mockito.same(mWebContents), Mockito.eq(constraints), Mockito.eq(current),164 Mockito.eq(animate));165 Mockito.clearInvocations(mJniMock);166 }167 private static class TestVisibilityDelegate extends BrowserControlsVisibilityDelegate {168 public TestVisibilityDelegate() {169 super(BrowserControlsState.BOTH);170 }171 }172}...
Source:PartnerBookmarksReaderTest.java
...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();53 }54 @Test55 public void partnerBrowserCustomizations_BookmarkEditingDisabled_NotAlreadyInitialized() {56 Mockito.when(mBrowserCustomizations.isInitialized()).thenReturn(false);57 @SuppressWarnings("unused")58 PartnerBookmarksReader reader =59 new PartnerBookmarksReader(mContextMock, mBrowserCustomizations);60 Mockito.verify(mBrowserCustomizations).initializeAsync(mContextMock);61 Mockito.when(mBrowserCustomizations.isBookmarksEditingDisabled()).thenReturn(true);62 mBrowserCustomizationsInitCallback.getValue().run();63 Mockito.verify(mJniMock).disablePartnerBookmarksEditing();64 }65 @Test66 public void partnerBrowserCustomizations_BookmarkEditingAllowed_AlreadyInitialized() {67 Mockito.when(mBrowserCustomizations.isInitialized()).thenReturn(true);68 @SuppressWarnings("unused")69 PartnerBookmarksReader reader =70 new PartnerBookmarksReader(mContextMock, mBrowserCustomizations);71 Mockito.verify(mBrowserCustomizations, Mockito.never()).initializeAsync(mContextMock);72 Mockito.when(mBrowserCustomizations.isBookmarksEditingDisabled()).thenReturn(false);73 mBrowserCustomizationsInitCallback.getValue().run();74 Mockito.verify(mJniMock, Mockito.never()).disablePartnerBookmarksEditing();75 }76 @Test77 public void partnerBrowserCustomizations_BookmarkEditingAllowed_NotAlreadyInitialized() {78 Mockito.when(mBrowserCustomizations.isInitialized()).thenReturn(false);79 @SuppressWarnings("unused")80 PartnerBookmarksReader reader =81 new PartnerBookmarksReader(mContextMock, mBrowserCustomizations);82 Mockito.verify(mBrowserCustomizations).initializeAsync(mContextMock);83 Mockito.when(mBrowserCustomizations.isBookmarksEditingDisabled()).thenReturn(false);84 mBrowserCustomizationsInitCallback.getValue().run();85 Mockito.verify(mJniMock, Mockito.never()).disablePartnerBookmarksEditing();86 }87 @Test88 public void partnerBookmarksCreationComplete_NotCalledWithoutBrowserCustomizations() {89 Mockito.when(mBrowserCustomizations.isInitialized()).thenReturn(true);90 @SuppressWarnings("unused")91 PartnerBookmarksReader reader =92 new PartnerBookmarksReader(mContextMock, mBrowserCustomizations);93 reader.onBookmarksRead();94 Mockito.verify(mJniMock, Mockito.never())95 .partnerBookmarksCreationComplete(Mockito.anyLong(), Mockito.any());96 }97 @Test98 public void partnerBookmarksCreationComplete_NotCalledWithoutBookmarksRead() {99 Mockito.when(mBrowserCustomizations.isInitialized()).thenReturn(true);100 @SuppressWarnings("unused")101 PartnerBookmarksReader reader =102 new PartnerBookmarksReader(mContextMock, mBrowserCustomizations);103 Mockito.when(mBrowserCustomizations.isBookmarksEditingDisabled()).thenReturn(false);104 mBrowserCustomizationsInitCallback.getValue().run();105 Mockito.verify(mJniMock, Mockito.never())106 .partnerBookmarksCreationComplete(Mockito.anyLong(), Mockito.any());107 }108 @Test109 public void partnerBookmarksCreationComplete_Called_WithCustomizationsFirstThenBookmarks() {110 Mockito.when(mBrowserCustomizations.isInitialized()).thenReturn(true);111 @SuppressWarnings("unused")112 PartnerBookmarksReader reader =113 new PartnerBookmarksReader(mContextMock, mBrowserCustomizations);114 Mockito.when(mBrowserCustomizations.isBookmarksEditingDisabled()).thenReturn(false);115 mBrowserCustomizationsInitCallback.getValue().run();116 reader.onBookmarksRead();117 Mockito.verify(mJniMock).partnerBookmarksCreationComplete(118 Mockito.anyLong(), Mockito.eq(reader));119 }120 @Test121 public void partnerBookmarksCreationComplete_Called_WithBookmarksFirstThenCustomizations() {122 Mockito.when(mBrowserCustomizations.isInitialized()).thenReturn(true);123 @SuppressWarnings("unused")124 PartnerBookmarksReader reader =125 new PartnerBookmarksReader(mContextMock, mBrowserCustomizations);126 Mockito.when(mBrowserCustomizations.isBookmarksEditingDisabled()).thenReturn(false);127 reader.onBookmarksRead();128 mBrowserCustomizationsInitCallback.getValue().run();129 Mockito.verify(mJniMock).partnerBookmarksCreationComplete(130 Mockito.anyLong(), Mockito.eq(reader));131 }132}...
Source:RedisSingleTest.java
...4import org.junit.Before;5import org.junit.Test;6import org.mockito.InjectMocks;7import org.mockito.Mock;8import org.mockito.Mockito;9import org.mockito.MockitoAnnotations;10import org.springframework.data.redis.connection.RedisClusterConnection;11import org.springframework.data.redis.connection.RedisConnection;12import org.springframework.data.redis.connection.jedis.JedisClusterConnection;13import org.springframework.data.redis.connection.jedis.JedisConnection;14import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;15import redis.clients.jedis.Jedis;16import redis.clients.jedis.JedisCluster;17import java.util.UUID;18/**19 * Function:20 *21 * @author crossoverJie22 * Date: 28/03/2018 23:3523 * @since JDK 1.824 */25public class RedisSingleTest {26 private RedisLock redisLock;27 @Mock28 private JedisConnectionFactory jedisConnectionFactory ;29 @Mock30 private Jedis jedis;31 @Before32 public void setBefore() {33 MockitoAnnotations.initMocks(this);34 redisLock = new RedisLock.Builder(jedisConnectionFactory, RedisToolsConstant.SINGLE)35 .lockPrefix("lock_")36 .sleepTime(100)37 .build();38 RedisConnection redisConnection = new JedisConnection(jedis) ;39 Mockito.when(jedisConnectionFactory.getConnection()).thenReturn(redisConnection);40 jedis = (Jedis)redisConnection.getNativeConnection();41 }42 @Test43 public void unlock() throws Exception {44 Mockito.when(jedis.eval(Mockito.anyString(), Mockito.anyList(), Mockito.anyList())).thenReturn(1L) ;45 boolean locktest = redisLock.unlock("test", "ec8ebca0-14ba0-4b23-99a8-b35fbba3629e");46 Assert.assertTrue(locktest);47 Mockito.verify(jedis).eval(Mockito.anyString(), Mockito.anyList(), Mockito.anyList());48 }49 @Test50 public void tryLock() throws Exception {51 String key = "test";52 String request = UUID.randomUUID().toString();53 Mockito.when(jedis.set(Mockito.anyString(), Mockito.anyString(),54 Mockito.anyString(), Mockito.anyString(), Mockito.anyInt()))55 .thenReturn("OK");56 boolean locktest = redisLock.tryLock(key, request);57 System.out.println("locktest=" + locktest);58 Assert.assertTrue(locktest);59 //check60 Mockito.verify(jedis).set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),61 Mockito.anyString(), Mockito.anyInt());62 }63 @Test64 public void lock() throws Exception {65 Mockito.when(jedis.set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),66 Mockito.anyString(), Mockito.anyInt())).thenReturn("OK");67 long start = System.currentTimeMillis();68 redisLock.lock("test", UUID.randomUUID().toString());69 long end = System.currentTimeMillis();70 System.out.println("lock success expire=" + (end - start));71 Mockito.verify(jedis).set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),72 Mockito.anyString(), Mockito.anyInt());73 }74 @Test75 public void lock2() throws Exception {76 Mockito.when(jedis.set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),77 Mockito.anyString(), Mockito.anyInt())).thenReturn("OK");78 long start = System.currentTimeMillis();79 boolean lock = redisLock.lock("test", UUID.randomUUID().toString(), 100);80 long end = System.currentTimeMillis();81 System.out.println("lock success expire=" + (end - start) + " lock = " + lock);82 Assert.assertTrue(lock);83 Mockito.verify(jedis).set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),84 Mockito.anyString(), Mockito.anyInt());85 }86 @Test87 public void lock2False() throws Exception {88 Mockito.when(jedis.set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),89 Mockito.anyString(), Mockito.anyInt())).thenReturn(null);90 long start = System.currentTimeMillis();91 boolean lock = redisLock.lock("test", UUID.randomUUID().toString(), 100);92 long end = System.currentTimeMillis();93 System.out.println("lock success expire=" + (end - start) + " lock = " + lock);94 Assert.assertFalse(lock);95 //check was called 2 times96 Mockito.verify(jedis,Mockito.times(2)).set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),97 Mockito.anyString(), Mockito.anyInt());98 }99 @Test100 public void tryLock2() throws Exception {101 Mockito.when(jedis.set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),102 Mockito.anyString(), Mockito.anyInt())).thenReturn("OK");103 boolean lock = redisLock.tryLock("test", UUID.randomUUID().toString(), 10 * 1000);104 Assert.assertTrue(lock);105 Mockito.verify(jedis).set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),106 Mockito.anyString(), Mockito.anyInt());107 }108 @Test109 public void tryLock2False() throws Exception {110 Mockito.when(jedis.set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),111 Mockito.anyString(), Mockito.anyInt())).thenReturn(null);112 boolean lock = redisLock.tryLock("test", UUID.randomUUID().toString(), 10 * 1000);113 Assert.assertFalse(lock);114 Mockito.verify(jedis).set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),115 Mockito.anyString(), Mockito.anyInt());116 }117}...
Source:ProjectPersistenceTest.java
...7import org.hibernate.SessionFactory;8import org.hibernate.criterion.Criterion;9import org.junit.Before;10import org.junit.Test;11import org.mockito.Mockito;12import com.globallogic.dogo.domain.Project;13import com.globallogic.dogo.mo.ProjectMO;14import com.globallogic.dogo.persistence.exception.ObjectNotFoundException;15public class ProjectPersistenceTest {16 17 private ProjectPersistence persistence;18 private SessionFactory mockedSessionFactory;19 private Session mockedSession;20 21 @Before22 public void setUp(){23 this.mockedSessionFactory = Mockito.mock(SessionFactory.class);24 this.mockedSession = Mockito.mock(Session.class);25 Mockito.when(mockedSessionFactory.openSession()).thenReturn(mockedSession);26 this.persistence = new ProjectPersistence(mockedSessionFactory);27 }28 29 @Test30 public void testList(){31 List<Project> mockedResult = new ArrayList<Project>();32 Criteria mockedCriteria = Mockito.mock(Criteria.class);33 Mockito.when(mockedSession.createCriteria(Project.class)).thenReturn(mockedCriteria);34 Mockito.when(mockedCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)).thenReturn(mockedCriteria);35 Mockito.when(mockedCriteria.list()).thenReturn(mockedResult);36 List<Project> result = this.persistence.list();37 Assert.assertNotNull(result);38 Assert.assertEquals(mockedResult, result);39 Mockito.verify(mockedSession,Mockito.times(1)).createCriteria(Project.class);40 Mockito.verify(mockedCriteria,Mockito.times(1)).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);41 Mockito.verify(mockedCriteria,Mockito.times(1)).list();42 Mockito.verify(mockedSession,Mockito.times(1)).close();43 }44 45 @Test46 public void testGet() throws ObjectNotFoundException{47 Project mockedResult = ProjectMO.build();48 Criteria mockedCriteria = Mockito.mock(Criteria.class);49 Mockito.when(mockedSession.createCriteria(Project.class)).thenReturn(mockedCriteria);50 Mockito.when(mockedCriteria.add(Mockito.any(Criterion.class))).thenReturn(mockedCriteria);51 Mockito.when(mockedCriteria.uniqueResult()).thenReturn(mockedResult);52 Project result = this.persistence.findById(ProjectMO.ID);53 Assert.assertNotNull(result);54 Assert.assertEquals(mockedResult, result);55 Mockito.verify(mockedSession,Mockito.times(1)).createCriteria(Project.class);56 Mockito.verify(mockedCriteria,Mockito.times(1)).add(Mockito.any(Criterion.class));57 Mockito.verify(mockedCriteria,Mockito.times(1)).uniqueResult();58 Mockito.verify(mockedSession,Mockito.times(1)).close();59 }60 61 @Test(expected = ObjectNotFoundException.class)62 public void testGetNull() throws ObjectNotFoundException{63 Criteria mockedCriteria = Mockito.mock(Criteria.class);64 Mockito.when(mockedSession.createCriteria(Project.class)).thenReturn(mockedCriteria);65 Mockito.when(mockedCriteria.add(Mockito.any(Criterion.class))).thenReturn(mockedCriteria);66 Mockito.when(mockedCriteria.uniqueResult()).thenReturn(null);67 Project result = this.persistence.findById(ProjectMO.ID);68 Assert.assertNull(result);69 Mockito.verify(mockedSession,Mockito.times(1)).createCriteria(Project.class);70 Mockito.verify(mockedCriteria,Mockito.times(1)).add(Mockito.any(Criterion.class));71 Mockito.verify(mockedCriteria,Mockito.times(1)).uniqueResult();72 Mockito.verify(mockedSession,Mockito.times(1)).close();73 }74 75 @Test76 public void testSave(){77 Project mockedProject = ProjectMO.build();78 this.persistence.create(mockedProject);79 Mockito.verify(mockedSession, Mockito.times(1)).save(mockedProject);80 Mockito.verify(mockedSession, Mockito.times(1)).flush();81 Mockito.verify(mockedSession, Mockito.times(1)).close();82 }83}...
Mockito
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.Mock;3import org.mockito.MockitoAnnotations;4import org.mockito.InjectMocks;5import org.mockito.runners.MockitoJUnitRunner;6import org.junit.runner.RunWith;7import org.junit.Before;8import org.junit.Test;9import static org.junit.Assert.*;10import static org.mockito.Mockito.*;11@RunWith(MockitoJUnitRunner.class)12public class Test1 {13private List mockedList;14public void setup() {15MockitoAnnotations.initMocks(this);16}17public void test() {18mockedList.add("one");19verify(mockedList).add("one");20}21}22import static org.mockito.Mockito.*;23import org.mockito.Mock;24import org.mockito.MockitoAnnotations;25import org.mockito.InjectMocks;26import org.mockito.runners.MockitoJUnitRunner;27import org.junit.runner.RunWith;28import org.junit.Before;29import org.junit.Test;30import static org.junit.Assert.*;31import java.util.List;32@RunWith(MockitoJUnitRunner.class)33public class Test1 {34private List mockedList;35public void setup() {36MockitoAnnotations.initMocks(this);37}38public void test() {39mockedList.add("one");40verify(mockedList).add("one");41}42}
Mockito
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.ArgumentCaptor;3import org.mockito.invocation.InvocationOnMock;4import org.mockito.stubbing.Answer;5import java.util.List;6public class 1 {7 public static void main(String[] args) {8 List mockedList = Mockito.mock(List.class);9 mockedList.add("one");10 mockedList.clear();11 Mockito.verify(mockedList).add("one");12 Mockito.verify(mockedList).clear();13 }14}15import org.mockito.Mockito;16import org.mockito.ArgumentCaptor;17import org.mockito.invocation.InvocationOnMock;18import org.mockito.stubbing.Answer;19import java.util.List;20public class 2 {21 public static void main(String[] args) {22 LinkedList mockedList = Mockito.mock(LinkedList.class);23 Mockito.when(mockedList.get(0)).thenReturn("first");24 System.out.println(mockedList.get(0));25 System.out.println(mockedList.get(999));26 }27}28import org.mockito.Mockito;29import org.mockito.ArgumentCaptor;30import org.mockito.invocation.InvocationOnMock;31import org.mockito.stubbing.Answer;32import java.util.List;33public class 3 {34 public static void main(String[] args) {35 LinkedList mockedList = Mockito.mock(LinkedList.class);36 Mockito.when(mockedList.get(Mockito.anyInt())).thenReturn("element");37 Mockito.when(mockedList.contains(Mockito.argThat(isValid()))).thenReturn("element");38 System.out.println(mockedList.get(999));39 Mockito.verify(mockedList).get(Mockito.anyInt());40 Mockito.verify(mock
Mockito
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.Mockito.*;3import org.mockito.Matchers.*;4import static org.mockito.Mockito.*;5import static org.mockito.Matchers.*;6import org.mockito.ArgumentCaptor;7import org.mockito.Captor;8import org.mockito.Mock;9import org.mockito.MockitoAnnotations;10import org.mockito.runners.MockitoJUnitRunner;11import org.mockito.stubbing.OngoingStubbing;12import org.mockito.stubbing.Stubber;13import org.mockito.invocation.InvocationOnMock;14import org.mockito.stubbing.Answer;15import org.mockito.verification.VerificationMode;16import org.mockito.exceptions.base.MockitoAssertionError;17import org.mockito.exceptions.verification.NeverWantedButInvoked;18import org.mockito.exceptions.verification.WantedButNotInvoked;19import org.mockito.exceptions.verification.NoInteractionsWanted;20import org.mockito.exceptions.verification.TooLittleActualInvocations;21import org.mockito.exceptions.verification.TooManyActualInvocations;22import org.mockito.exceptions.verification.VerificationInOrderFailure;23import org.mockito.exceptions.verification.VerificationAsse
Mockito
Using AI Code Generation
1import java.util.List;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.when;4import static org.mockito.Mockito.verify;5import static org.mockito.Mockito.times;6import static org.mockito.Mockito.doNothing;7import static org.mockito.Mockito.doThrow;8import static org.mockito.Mockito.doReturn;9import static org.mockito.Mockito.spy;10import static org.mockito.Mockito.doCallRealMethod;11import static org.mockito.Mockito.doAnswer;12import static org.mockito.Mockito.doNothing;13import static org.mockito.Mockito.inOrder;14import static org.mockito.Mockito.atLeastOnce;15import static org.mockito.Mockito.atLeast;16import static org.mockito.Mockito.atMost;17import static org.mockito.Mockito.never;18import static org.mockito.Mockito.only;19import static org.mockito.Mockito.timeout;20import static org.mockito.Mockito.verifyNoMoreInteractions;21import static org.mockito.Mockito.verifyZeroInteractions;22import static org.m
Mockito
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.invocation.InvocationOnMock;3import org.mockito.stubbing.Answer;4public class MockitoExample {5 public static void main(String[] args) {6 TestClass mockObj = Mockito.mock(TestClass.class);7 Answer<Integer> answer = new Answer<Integer>() {8 public Integer answer(InvocationOnMock invocation) {9 Object[] args = invocation.getArguments();10 Integer arg1 = (Integer) args[0];11 Integer arg2 = (Integer) args[1];12 return arg1 + arg2;13 }14 };15 Mockito.when(mockObj.add(5, 10)).thenAnswer(answer);16 System.out.println(mockObj.add(5, 10));17 }18}19Mockito verify() Method Example20Mockito doReturn() Method Example21Mockito doThrow() Method Example22Mockito doCallRealMethod() Method Example23Mockito doNothing() Method Example24Mockito doAnswer() Method Example25Mockito spy() Method Example26Mockito mock() Method Example27Mockito reset() Method Example28Mockito timeout() Method Example29Mockito verifyNoMoreInteractions() Method Example30Mockito verifyNoInteractions() Method Example31Mockito verifyZeroInteractions() Method Example32Mockito verifyNoMoreInteractions() Method Example33Mockito verify() Method Example34Mockito verify() Method Example35Mockito times() Method Example36Mockito atLeastOnce() Method Example37Mockito atLeast() Method Example38Mockito atMost() Method Example39Mockito never() Method Example40Mockito only() Method Example41Mockito doThrow() Method Example42Mockito doReturn() Method Example43Mockito doNothing() Method Example44Mockito doCallRealMethod() Method Example45Mockito doAnswer() Method Example
Mockito
Using AI Code Generation
1import org.mockito.Mockito;2import static org.mockito.Mockito.*;3public class MyClass {4 public int myMethod(int a, int b) {5 return a + b;6 }7}8public class TestClass {9 public void testMethod() {10 MyClass test = Mockito.mock(MyClass.class);11 when(test.myMethod(1, 2)).thenReturn(3);12 assertEquals(3, test.myMethod(1, 2));13 }14}15import org.mockito.Mockito;16import static org.mockito.Mockito.*;17public class MyClass {18 public int myMethod(int a, int b) {19 return a + b;20 }21}22public class TestClass {23 public void testMethod() {24 MyClass test = Mockito.mock(MyClass.class);25 when(test.myMethod(1, 2)).thenReturn(3);26 assertEquals(3, test.myMethod(1, 2));27 }28}29import org.mockito.Mockito;30import static org.mockito.Mockito.*;31public class MyClass {32 public int myMethod(int a, int b) {33 return a + b;34 }35}36public class TestClass {37 public void testMethod() {38 MyClass test = Mockito.mock(MyClass.class);39 when(test.myMethod(1, 2)).thenReturn(3);40 assertEquals(3, test.myMethod(1, 2));41 }42}43import org.mockito.Mockito;44import static org.mockito.Mockito.*;45public class MyClass {46 public int myMethod(int a, int b) {47 return a + b;48 }49}50public class TestClass {51 public void testMethod() {52 MyClass test = Mockito.mock(MyClass.class);53 when(test.myMethod(1, 2)).thenReturn(3);54 assertEquals(3, test.myMethod(1, 2));55 }56}57import org.mockito.Mockito;58import static org.mockito.Mockito.*;
Mockito
Using AI Code Generation
1import org.mockito.Mockito;2public class Test1 {3public static void main(String[] args) {4 Test t = Mockito.mock(Test.class);5 Mockito.when(t.add(10, 20)).thenReturn(30);6 Mockito.when(t.add(20, 20)).thenReturn(40);7 System.out.println(t.add(10, 20));8 System.out.println(t.add(20, 20));9}10}
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!!