Best Mockito code snippet using org.mockito.Mockito.only
Source:OfficalTest_Part_3.java
...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:AsyncStorageModuleTest.java
...246 }247 }248 });249 // Test removal in same test, since it's costly to set up the test again.250 // Remove only odd keys251 JavaOnlyArray keyRemoves = new JavaOnlyArray();252 for (int i = 0; i < keyCount; i++) {253 if (i % 2 > 0) {254 keyRemoves.pushString("key" + i);255 }256 }257 mStorage.multiRemove(keyRemoves, mock(Callback.class));258 mStorage.getAllKeys(259 new Callback() {260 @Override261 public void invoke(Object... args) {262 JavaOnlyArray resultArray = (JavaOnlyArray) args[1];263 assertThat(resultArray.size()).isEqualTo(499);264 for (int i = 0; i < resultArray.size(); i++) {...
Source:DepartmentControllerTest.java
1package com.employee.management.controller;23import static org.junit.Assert.assertEquals;4import static org.mockito.Mockito.only;5import static org.mockito.Mockito.times;6import static org.mockito.Mockito.verify;7import static org.mockito.Mockito.verifyNoMoreInteractions;8import static org.mockito.Mockito.verifyZeroInteractions;9import static org.mockito.Mockito.when;1011import java.util.ArrayList;12import java.util.List;13import java.util.Optional;1415import org.junit.AfterClass;16import org.junit.Assert;17import org.junit.Before;18import org.junit.BeforeClass;19import org.junit.Test;20import org.mockito.InjectMocks;21import org.mockito.Mock;22import org.mockito.Mockito;23import org.mockito.MockitoAnnotations;24import org.mockito.Spy;2526import com.employee.management.error.DepartmentErrorCodes;27import com.employee.management.exception.DepartmentException;28import com.employee.management.model.Department;29import com.employee.management.service.DepartmentServiceImpl;3031/* To Enable Mockito Annotations :32 Need to annotate the JUnit test with a runnerâ MockitoJUnitRunner33Example:3435@RunWith(MockitoJUnitRunner.class)36public class MockitoAnnotationTest {37 ...38}3940Alternatively we can enable these annotations programmatically as well, by invoking MockitoAnnotations.initMocks()41Example:42@Before43public void init() {44 MockitoAnnotations.initMocks(this);45}46*/47public class DepartmentControllerTest {48 /*49 * @Mock Annotation is used to create and inject mocked instances without having50 * to call Mockito.mockmanually.51 * 52 */5354 @Mock55 DepartmentServiceImpl departmentService;5657 /*58 * @InjectMocksannotation â to inject mock fields into the tested object59 * automatically.60 */61 @InjectMocks62 DepartmentController departmentController;6364 static Department departmentOne;6566 static Department departmentTwo;6768 Department departmentThree;69 static Optional<Department> deparmentOptional;7071 static List<Department> list;7273 // Sample test case for the before class annotation7475 @BeforeClass76 public static void beforeClassTestCase() {7778 /**79 * This method will be called only once per test class. It will be called before80 * executing test.81 */82 list = new ArrayList<Department>();83 departmentOne = new Department(7, "XYZ Department", "XYZ");84 departmentTwo = new Department(4, "ABC Department", "ABC");85 list.add(departmentOne);86 list.add(departmentTwo);87 deparmentOptional = Optional.of(departmentOne);88 System.out.println("Using @BeforeClass ,executed after all test cases");89 }9091 /**92 * This method will be called be before every test cases execution.93 * 94 */95 @Before96 public void setUp() {97 /*98 * initMocks Initializes objects annotated with Mockito annotations for given99 * testClass: @Mock, @Spy, @InjectMocks100 */101 MockitoAnnotations.initMocks(this);102 System.out.println("Executed before every Test cases");103 }104 /*105 * Sample example that call the real method of the mocked class here after106 * mocking the Department service class we can call the actual method by calling107 * the doCallRealMethod Method108 */109110 @Test111 public void testGetHarcodedEmployeeList() {112 List<Department> expectedlist = new ArrayList<>();113 expectedlist.add(new Department(10, "XYZ Departemnt", "XYZ"));114 Mockito.doCallRealMethod().when(departmentService).getHarcodedEmployeeList();115 List<Department> dptlist = departmentController.getHarcodedDepartment();116 Assert.assertNotNull(dptlist);117 assertEquals(expectedlist.size(), dptlist.size());118 /* Sample example to show that the mocked method is called 2 no of times */119 verify(departmentService, times(2)).getHarcodedEmployeeList();120 verifyNoMoreInteractions(departmentService);121 }122123 @Test124 public void testGetAllEmployees() {125 when(departmentService.getAllDepartments()).thenReturn(list);126 List<Department> departmentList = departmentController.getAllDepartment();127 Assert.assertEquals(list.size(), departmentList.size());128 Assert.assertEquals(list, departmentList);129 /*130 * Allows checking if given method was the only one invoked. E.g:131 * 132 * verify(mock, only()).someMethod(); //above is a shorthand for following 2133 * lines of code: verify(mock).someMethod(); verifyNoMoreInteractions(mock);134 * 135 */136 verify(departmentService).getAllDepartments();137 verifyNoMoreInteractions(departmentService);138 System.out.println("testGetAllEmployees");139 }140141 @Test142 public void testGetEmployee() {143 when(departmentService.getDepartment(Mockito.anyInt())).thenReturn(departmentOne);144 Department department = departmentController.getDepartment(7);145 Assert.assertEquals(departmentOne.getDepartment_Name(), department.getDepartment_Name());146 Assert.assertEquals(departmentOne.getShort_Name(), department.getShort_Name());147 Assert.assertEquals(departmentOne.getDepartment_ID(), department.getDepartment_ID());148 /*149 * Allows checking if given method was the only one invoked. E.g:150 * 151 * verify(mock, only()).someMethod();152 * 153 * //above is a shorthand for following 2 lines of code:154 * 155 * verify(mock).someMethod(); verifyNoMoreInteractions(mock);156 * 157 */158 verify(departmentService, only()).getDepartment(Mockito.anyInt());159 System.out.println("testGetEmployee");160 }161162 /*163 * This annotation can be used if you want to handle some exception during test164 * execution. For, e.g., if you want to check whether a particular method is165 * throwing specified exception or not.166 * 167 */168169 @Test(expected = DepartmentException.class)170 public void testGetEmployeeDepaertmentException() {171 when(departmentService.getDepartment(Mockito.anyInt())).thenReturn(departmentOne);172 departmentController.getDepartment(-3);173 }174175 @Test176 public void testAddEmployee() {177 Mockito.doNothing().when(departmentService).addDepartment(Mockito.any(Department.class));178 departmentController.addDepartment(departmentOne);179 verify(departmentService, only()).addDepartment(Mockito.any(Department.class));180 System.out.println("testAddEmployee");181 }182183 @Test184 public void testUpdateEmployee() {185 when(departmentService.getDepartment(Mockito.anyInt())).thenReturn(departmentOne);186 Mockito.doNothing().when(departmentService).updateDepartment(Mockito.<Department>any(), Mockito.anyInt());187 departmentController.updateDepartment(departmentOne, 7);188 verify(departmentService).getDepartment(Mockito.anyInt());189 verify(departmentService).updateDepartment(Mockito.any(Department.class), Mockito.anyInt());190 verifyNoMoreInteractions(departmentService);191 System.out.println("testUpdateEmployee");192 }193194 @Test195 public void testDeleteAllEmployees() {196 departmentController.deleteAllDepartments();197 verify(departmentService, only()).deleteAllDepartment();198 System.out.println("testDeleteAllEmployees");199 }200201 @Test202 public void testDeleteEmployeeById() {203 departmentController.deleteDepartmentByID(departmentOne, 7);204 verify(departmentService, only()).deleteDepartmentByID(Mockito.anyInt());205 System.out.println("testDeleteEmployeeById");206 }207208 /*209 * Uncomment the Ignore Annotation to show how the test case get Ignore while210 * executing.211 */212 // @Ignore213 @Test214 public void testPatchEmployeeById() {215 departmentController.patchDepartmentByID(departmentOne, 7);216 verify(departmentService, only()).patchDepartment(Mockito.any(Department.class), Mockito.anyInt());217 System.out.println("testPatchEmployeeById");218 }219220 /*221 * This is the sample test case to test the exception scenario using try catch222 * in the test method and also we can verify about the exception messages and error codes using this approach 223 * 224 */225 @Test226 public void addDepartmentNegativeDepartmentIdException() {227 /* Sample example verify for the zero interaction */228 DepartmentErrorCodes expectedErrorCode = DepartmentErrorCodes.DEPARTMENT_NAME_EXCEPTION;229 try {230 departmentThree = new Department(-4, "ABC Department", "ABC");231 departmentController.addDepartment(departmentThree);232 } catch (DepartmentException exception) {233 //add comment234 assertEquals(expectedErrorCode, exception.getErrorCodes());235 verifyZeroInteractions(departmentService);236 }237 }238239 // Sample test case for the after class annotation240241 @AfterClass242 public static void aftreClassTestCase() {243 /**244 * This method will be called only once per test class. It will be called after245 * executing test.246 */247 list = null;248 System.out.println("Using @AfterClass ,executed after all test cases");249 }250251}
...
Source:StackTraceFilterTest.java
...3 * This program is made available under the terms of the MIT License.4 */5package org.mockito.internal.exceptions.stacktrace;6import static org.junit.Assert.assertEquals;7import static org.mockitoutil.Conditions.onlyThoseClasses;8import org.assertj.core.api.Assertions;9import org.junit.Test;10import org.mockito.exceptions.base.TraceBuilder;11import org.mockitoutil.TestBase;12public class StackTraceFilterTest extends TestBase {13 private final StackTraceFilter filter = new StackTraceFilter();14 @Test15 public void shouldFilterOutCglibGarbage() {16 StackTraceElement[] t =17 new TraceBuilder()18 .classes("MockitoExampleTest", "List$$EnhancerByMockitoWithCGLIB$$2c406024")19 .toTraceArray();20 StackTraceElement[] filtered = filter.filter(t, false);21 Assertions.assertThat(filtered).has(onlyThoseClasses("MockitoExampleTest"));22 }23 @Test24 public void shouldFilterOutByteBuddyGarbage() {25 StackTraceElement[] t =26 new TraceBuilder()27 .classes(28 "MockitoExampleTest",29 "org.testcase.MockedClass$MockitoMock$1882975947.doSomething(Unknown Source)")30 .toTraceArray();31 StackTraceElement[] filtered = filter.filter(t, false);32 Assertions.assertThat(filtered).has(onlyThoseClasses("MockitoExampleTest"));33 }34 @Test35 public void shouldFilterOutMockitoPackage() {36 StackTraceElement[] t =37 new TraceBuilder()38 .classes("org.test.MockitoSampleTest", "org.mockito.Mockito")39 .toTraceArray();40 StackTraceElement[] filtered = filter.filter(t, false);41 Assertions.assertThat(filtered).has(onlyThoseClasses("org.test.MockitoSampleTest"));42 }43 @Test44 public void shouldNotFilterOutTracesMiddleGoodTraces() {45 StackTraceElement[] t =46 new TraceBuilder()47 .classes(48 "org.test.MockitoSampleTest",49 "org.test.TestSupport",50 "org.mockito.Mockito",51 "org.test.TestSupport",52 "org.mockito.Mockito")53 .toTraceArray();54 StackTraceElement[] filtered = filter.filter(t, false);55 Assertions.assertThat(filtered)56 .has(57 onlyThoseClasses(58 "org.test.TestSupport",59 "org.test.TestSupport",60 "org.test.MockitoSampleTest"));61 }62 @Test63 public void shouldKeepRunners() {64 StackTraceElement[] t =65 new TraceBuilder()66 .classes(67 "org.mockito.runners.Runner",68 "junit.stuff",69 "org.test.MockitoSampleTest",70 "org.mockito.Mockito")71 .toTraceArray();72 StackTraceElement[] filtered = filter.filter(t, false);73 Assertions.assertThat(filtered)74 .has(75 onlyThoseClasses(76 "org.test.MockitoSampleTest",77 "junit.stuff",78 "org.mockito.runners.Runner"));79 }80 @Test81 public void shouldNotFilterElementsAboveMockitoJUnitRule() {82 StackTraceElement[] t =83 new TraceBuilder()84 .classes(85 "org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:16)",86 "org.mockito.runners.Runner",87 "junit.stuff",88 "org.test.MockitoSampleTest",89 "org.mockito.internal.MockitoCore.verifyNoMoreInteractions",90 "org.mockito.internal.debugging.LocationImpl")91 .toTraceArray();92 StackTraceElement[] filtered = filter.filter(t, false);93 Assertions.assertThat(filtered)94 .has(95 onlyThoseClasses(96 "org.test.MockitoSampleTest",97 "junit.stuff",98 "org.mockito.runners.Runner",99 "org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:16)"));100 }101 @Test102 public void shouldKeepInternalRunners() {103 StackTraceElement[] t =104 new TraceBuilder()105 .classes(106 "org.mockito.internal.runners.Runner", "org.test.MockitoSampleTest")107 .toTraceArray();108 StackTraceElement[] filtered = filter.filter(t, false);109 Assertions.assertThat(filtered)110 .has(111 onlyThoseClasses(112 "org.test.MockitoSampleTest",113 "org.mockito.internal.runners.Runner"));114 }115 @Test116 public void shouldStartFilteringAndKeepTop() {117 // given118 StackTraceElement[] t =119 new TraceBuilder()120 .classes(121 "org.test.Good",122 "org.mockito.internal.Bad",123 "org.test.MockitoSampleTest")124 .toTraceArray();125 // when126 StackTraceElement[] filtered = filter.filter(t, true);127 // then128 Assertions.assertThat(filtered)129 .has(onlyThoseClasses("org.test.MockitoSampleTest", "org.test.Good"));130 }131 @Test132 public void133 shouldKeepGoodTraceFromTheTopBecauseRealImplementationsOfSpiesSometimesThrowExceptions() {134 StackTraceElement[] t =135 new TraceBuilder()136 .classes(137 "org.good.Trace",138 "org.yet.another.good.Trace",139 "org.mockito.internal.to.be.Filtered",140 "org.test.MockitoSampleTest")141 .toTraceArray();142 StackTraceElement[] filtered = filter.filter(t, true);143 Assertions.assertThat(filtered)144 .has(145 onlyThoseClasses(146 "org.test.MockitoSampleTest",147 "org.yet.another.good.Trace",148 "org.good.Trace"));149 }150 @Test151 public void shouldReturnEmptyArrayWhenInputIsEmpty() throws Exception {152 // when153 StackTraceElement[] filtered = filter.filter(new StackTraceElement[0], false);154 // then155 assertEquals(0, filtered.length);156 }157}...
Source:EnhancedCookieGeneratorTest.java
...5 * All rights reserved.6 *7 * This software is the confidential and proprietary information of hybris8 * ("Confidential Information"). You shall not disclose such Confidential9 * Information and shall use it only in accordance with the terms of the10 * license agreement you entered into with hybris.11 *12 * 13 */14package com.jnj.b2b.storefront.security.cookie;15import javax.servlet.http.Cookie;16import javax.servlet.http.HttpServletRequest;17import javax.servlet.http.HttpServletResponse;18import org.apache.commons.lang.builder.ToStringBuilder;19import org.junit.Assert;20import org.junit.Before;21import org.junit.Test;22import org.mockito.ArgumentMatcher;23import org.mockito.BDDMockito;...
Source:HomepagePromoVariationManagerTest.java
...73 Mockito.verify(mStudyHelper, times(1)).registerSyntheticFieldTrial(STUDY_ENABLED_GROUP);74 Mockito.verify(mStudyHelper, never()).registerSyntheticFieldTrial(STUDY_TRACKING_GROUP);75 }76 /**77 * If study disabled and client in tracking-only, STUDY_TRACKING_GROUP should be tagged in78 * SyntheticFieldTrial.79 */80 @Test81 @SmallTest82 public void testStudyDisabled_TrackingGroup() {83 setStudyHelper(true, false, true);84 HomepagePromoVariationManager.getInstance().tagSyntheticHomepagePromoSeenGroup();85 Mockito.verify(mStudyHelper, times(1)).isClientInIPHTrackingOnlyGroup();86 Mockito.verify(mStudyHelper, never()).isClientInEnabledStudyGroup();87 Mockito.verify(mStudyHelper, times(1)).isClientInTrackingStudyGroup();88 Mockito.verify(mStudyHelper, never()).registerSyntheticFieldTrial(STUDY_ENABLED_GROUP);89 Mockito.verify(mStudyHelper, times(1)).registerSyntheticFieldTrial(STUDY_TRACKING_GROUP);90 }91 /**...
Source:LineMessagingClientBuilderTest.java
1package com.linecorp.bot.client;2import static org.assertj.core.api.Assertions.assertThat;3import static org.mockito.Mockito.mock;4import static org.mockito.Mockito.only;5import static org.mockito.Mockito.verify;6import static org.mockito.Mockito.when;7import org.junit.Before;8import org.junit.Rule;9import org.junit.Test;10import org.mockito.Mock;11import org.mockito.internal.util.reflection.Whitebox;12import org.mockito.junit.MockitoJUnit;13import org.mockito.junit.MockitoRule;14import okhttp3.Interceptor;15import okhttp3.mockwebserver.RecordedRequest;16public class LineMessagingClientBuilderTest extends AbstractWiremockTest {17 @Rule18 public final MockitoRule mockitoRule = MockitoJUnit.rule();19 @Mock20 LineMessagingService lineMessagingServiceMock;21 @Mock22 LineMessagingServiceBuilder delegateMock;23 LineMessagingClientBuilder builder;24 @Before25 public void setUp() throws Exception {26 builder = LineMessagingClient.builder("FIXED_TOKEN");27 Whitebox.setInternalState(builder, "delegate", delegateMock);28 }29 @Test30 public void setterTestForApiEndPoint() {31 // Do32 builder.apiEndPoint("https://example.com");33 // Verify34 verify(delegateMock, only()).apiEndPoint("https://example.com");35 }36 @Test37 public void setterTestForConnectTimeout() {38 // Do39 builder.connectTimeout(1234);40 // Verify41 verify(delegateMock, only()).connectTimeout(1234);42 }43 @Test44 public void setterTestForReadTimeout() {45 // Do46 builder.readTimeout(1234);47 // Verify48 verify(delegateMock, only()).readTimeout(1234);49 }50 @Test51 public void setterTestForWriteTimeout() {52 // Do53 builder.writeTimeout(1234);54 // Verify55 verify(delegateMock, only()).writeTimeout(1234);56 }57 @Test58 public void setterTestForAddInterceptorTimeout() {59 final Interceptor mock = mock(Interceptor.class);60 // Do61 builder.addInterceptor(mock);62 // Verify63 verify(delegateMock, only()).addInterceptor(mock);64 }65 @Test66 public void setterTestForAddInterceptorFirst() {67 final Interceptor mock = mock(Interceptor.class);68 // Do69 builder.addInterceptorFirst(mock);70 // Verify71 verify(delegateMock, only()).addInterceptorFirst(mock);72 }73 @Test74 public void setterTestForRemoveAllInterceptors() {75 // Do76 builder.removeAllInterceptors();77 // Verify78 verify(delegateMock, only()).removeAllInterceptors();79 }80 @Test81 public void setterTestForOkHttpClientBuilder() {82 // We cant check because Builder is final and can't be mocked.83 }84 @Test85 public void setterTestForRetrofitBuilder() {86 // We cant check because Builder is final and can't be mocked.87 }88 @Test89 public void testBuilderWithChannelTokenSupplier() throws InterruptedException {90 final LineMessagingClient lineMessagingClient =91 LineMessagingClient.builder(() -> "MOCKED_TOKEN")92 .apiEndPoint("http://localhost:" + mockWebServer.getPort())93 .build();94 // Do95 lineMessagingClient.getProfile("TEST");96 // Verify97 final RecordedRequest recordedRequest = mockWebServer.takeRequest();98 assertThat(recordedRequest.getHeader("Authorization"))99 .isEqualTo("Bearer MOCKED_TOKEN");100 }101 @Test102 public void testBuild() {103 when(delegateMock.build()).thenReturn(lineMessagingServiceMock);104 // Do105 LineMessagingClient result = builder.build();106 // Verify107 verify(delegateMock, only()).build();108 assertThat(result)109 .isInstanceOf(LineMessagingClientImpl.class)110 .hasFieldOrPropertyWithValue("retrofitImpl", lineMessagingServiceMock);111 }112}...
Source:Strictness.java
...23 * Enable it via {@link MockitoRule}, {@link MockitoJUnitRunner} or {@link MockitoSession}.24 * See {@link #STRICT_STUBS} for the details.</li>25 * <li>{@link Strictness#LENIENT} - no added behavior.26 * The default of Mockito 1.x.27 * Recommended only if you cannot use {@link #STRICT_STUBS}</li>28 * <li>{@link Strictness#WARN} - cleaner tests but only if you read the console output.29 * Reports console warnings about unused stubs30 * and stubbing argument mismatch (see {@link org.mockito.quality.MockitoHint}).31 * The default behavior of Mockito 2.x when {@link JUnitRule} or {@link MockitoJUnitRunner} are used.32 * Recommended if you cannot use {@link #STRICT_STUBS}.33 * Introduced originally with Mockito 2 because console warnings was the only compatible way of adding such feature.</li>34 * </ol>35 *36 * @since 2.3.037 */38public enum Strictness {39 /**40 * No extra strictness. Mockito 1.x behavior.41 * Recommended only if you cannot use {@link #STRICT_STUBS}.42 * <p>43 * For more information see {@link Strictness}.44 *45 * @since 2.3.046 */47 LENIENT,48 /**49 * Helps keeping tests clean and improves debuggability only if you read the console output.50 * Extra warnings emitted to the console, see {@link MockitoHint}.51 * Default Mockito 2.x behavior.52 * Recommended only if you cannot use {@link #STRICT_STUBS} because console output is ignored most of the time.53 * <p>54 * For more information see {@link Strictness}.55 *56 * @since 2.3.057 */58 WARN,59 /**60 * Ensures clean tests, reduces test code duplication, improves debuggability.61 * Offers best combination of flexibility and productivity.62 * Highly recommended.63 * Planned as default for Mockito v4.64 * Enable it via our JUnit support ({@link MockitoJUnit}) or {@link MockitoSession}.65 * <p>66 * Adds following behavior:...
only
Using AI Code Generation
1package org.mockito;2public class Mockito {3 public static <T> T mock(Class<T> classToMock) {4 return null;5 }6}7package org.mockito;8public class Mockito {9 public static <T> T mock(Class<T> classToMock) {10 return null;11 }12}13package org.mockito;14public class Mockito {15 public static <T> T mock(Class<T> classToMock) {16 return null;17 }18}19package org.mockito;20public class Mockito {21 public static <T> T mock(Class<T> classToMock) {22 return null;23 }24}25package org.mockito;26public class Mockito {27 public static <T> T mock(Class<T> classToMock) {28 return null;29 }30}31package org.mockito;32public class Mockito {33 public static <T> T mock(Class<T> classToMock) {34 return null;35 }36}37package org.mockito;38public class Mockito {39 public static <T> T mock(Class<T> classToMock) {40 return null;41 }42}43package org.mockito;44public class Mockito {45 public static <T> T mock(Class<T> classToMock) {46 return null;47 }48}49package org.mockito;50public class Mockito {51 public static <T> T mock(Class<T> classToMock) {52 return null;53 }54}55package org.mockito;56public class Mockito {57 public static <T> T mock(Class<T> classToMock) {58 return null;59 }60}
only
Using AI Code Generation
1import static org.mockito.Mockito.*;2import org.mockito.Mockito;3import org.mockito.Mock;4import org.mockito.InjectMocks;5import org.mockito.runners.MockitoJUnitRunner;6import org.junit.runner.RunWith;7import org.junit.Test;8import org.junit.Before;9import org.junit.After;10@RunWith(MockitoJUnitRunner.class)11public class 1 {12 private 2 3;13 private 4 5;14 public void setUp() throws Exception {15 }16 public void tearDown() throws Exception {17 }18 public void 6() throws Exception {19 }20}21import org.mockito.Mockito;22import org.mockito.Mock;23import org.mockito.InjectMocks;24import org.mockito.runners.MockitoJUnitRunner;25import org.junit.runner.RunWith;26import org.junit.Test;27import org.junit.Before;28import org.junit.After;29@RunWith(MockitoJUnitRunner.class)30public class 2 {31 private 3 4;32 private 5 6;33 public void setUp() throws Exception {34 }35 public void tearDown() throws Exception {36 }37 public void 7() throws Exception {38 }39}40import org.mockito.Mockito;41import org.mockito.Mock;42import org.mockito.InjectMocks;43import org.mockito.runners.MockitoJUnitRunner;44import org.junit.runner.RunWith;45import org.junit.Test;46import org.junit.Before;47import org.junit.After;48@RunWith(MockitoJUnitRunner.class)49public class 3 {50 private 4 5;51 private 6 7;52 public void setUp() throws Exception {53 }54 public void tearDown() throws Exception {55 }56 public void 8() throws Exception {57 }58}59import org.mockito.Mockito;60import org.mockito.Mock
only
Using AI Code Generation
1import static org.mockito.Mockito.*;2import org.mockito.Mockito;3public class 1 {4 public static void main(String[] args) {5 List mockedList = mock(List.class);6 mockedList.add("one");7 mockedList.clear();8 verify(mockedList).add("one");9 verify(mockedList).clear();10 }11}12import static org.mockito.Mockito.*;13import org.mockito.Mockito;14public class 2 {15 public static void main(String[] args) {16 LinkedList mockedList = mock(LinkedList.class);17 when(mockedList.get(0)).thenReturn("first");18 System.out.println(mockedList.get(0));19 System.out.println(mockedList.get(999));20 }21}22import static org.mockito.Mockito.*;23import org.mockito.Mockito;24public class 3 {25 public static void main(String[] args) {26 LinkedList mockedList = mock(LinkedList.class);27 when(mockedList.get(0)).thenReturn("first");28 when(mockedList.get(1)).thenThrow(new RuntimeException());29 System.out.println(mockedList.get(0));30 System.out.println(mockedList.get(1));31 System.out.println(mockedList.get(999));32 }33}34import static org.mockito.Mockito.*;35import org.mockito.Mockito;36public class 4 {37 public static void main(String[] args) {38 LinkedList mockedList = mock(LinkedList.class);39 when(mockedList.get(anyInt())).thenReturn("
only
Using AI Code Generation
1import static org.mockito.Mockito.*;2import org.mockito.Mockito;3import org.junit.Test;4import org.junit.runner.RunWith;5import org.mockito.Mock;6import org.mockito.runners.MockitoJUnitRunner;7import org.mockito.invocation.InvocationOnMock;8import org.mockito.stubbing.Answer;9import static org.junit.Assert.*;10import org.junit.Before;11import org.mockito.ArgumentCaptor;12import org.mockito.Captor;13@RunWith(MockitoJUnitRunner.class)14public class TestClass {15 private SomeClass mock;16 private ArgumentCaptor<String> captor;17 public void setUp() {18 when(mock.someMethod(captor.capture())).thenAnswer(19 new Answer<Boolean>() {20 public Boolean answer(InvocationOnMock invocation) {21 Object[] args = invocation.getArguments();22 Object mock = invocation.getMock();23 return "some argument".equals(args[0]);24 }25 });26 }27 public void test() {28 assertTrue(mock.someMethod("some argument"));29 assertEquals("some argument", captor.getValue());30 }31}32import static org.mockito.Mockito.*;33import org.mockito.Mockito;34import org.junit.Test;35import org.junit.runner.RunWith;36import org.mockito.Mock;37import org.mockito.runners.MockitoJUnitRunner;38import org.mockito.invocation.InvocationOnMock;39import org.mockito.stubbing.Answer;40import static org.junit.Assert.*;41import org.junit.Before;42import org.mockito.ArgumentCaptor;43import org.mockito.Captor;44@RunWith(MockitoJUnitRunner.class)45public class TestClass {46 private SomeClass mock;47 private ArgumentCaptor<String> captor;48 public void setUp() {49 when(mock.someMethod(captor.capture())).thenAnswer(50 new Answer<Boolean>() {51 public Boolean answer(InvocationOnMock invocation) {52 Object[] args = invocation.getArguments();53 Object mock = invocation.getMock();54 return "some argument".equals(args[0]);55 }56 });57 }58 public void test() {59 assertTrue(mock.someMethod("some argument"));60 assertEquals("some argument", captor.getValue());61 }62}63import static org.mockito.Mockito.*;64import org.mockito.Mockito;65import org.junit.Test;66import org.junit.runner.RunWith;
only
Using AI Code Generation
1import org.mockito.Mockito;2public class Test {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}11import static org.mockito.Mockito.*;12public class Test {13 public static void main(String[] args) {14 List mockedList = mock(List.class);15 mockedList.add("one");16 mockedList.clear();17 verify(mockedList).add("one");18 verify(mockedList).clear();19 }20}21import static org.mockito.Mockito.*;22public class Test {23 public static void main(String[] args) {24 List mockedList = mock(List.class);25 when(mockedList.get(0)).thenReturn("first");26 when(mockedList.get(1)).thenThrow(new RuntimeException());27 System.out.println(mockedList.get(0));28 System.out.println(mockedList.get(1));29 System.out.println(mockedList.get(999));30 }31}32import static org.mockito.Mockito.*;33public class Test {34 public static void main(String[] args) {35 Iterator i = mock(Iterator.class);36 when(i.next()).thenReturn("Hello").thenReturn("Mockito");37 String result = i.next() + " " + i.next();38 assertEquals("Hello Mockito", result);39 }40}41import static org.mockito.Mockito.*;42public class Test {43 public static void main(String[] args) {44 List mockedList = mock(List.class);45 when(mockedList.get(anyInt())).thenReturn("element");
only
Using AI Code Generation
1import org.mockito.Mockito;2public class 1 {3public static void main(String[] args) {4Mockito mockito = Mockito.mock(Mockito.class);5}6}7Mockito mockito = Mockito.mock(Mockito.class);8The correct way to use the mock() method is as follows:9import org.mockito.Mockito;10public class 1 {11public static void main(String[] args) {12Mockito mockito = mock(Mockito.class);13}14}15Mockito mockito = mock(Mockito.class);16The correct way to use the mock() method is as follows:17import org.mockito.Mockito;18public class 1 {19public static void main(String[] args) {20Mockito mockito = Mockito.mock(Mockito.class);21}22}23at 1.main(1.java:7)24at org.mockito.internal.creation.instance.InstantiatorProviderFactory.getInstantiatorProvider(InstantiatorProviderFactory.java:16)25at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.<clinit>(SubclassBytecodeGenerator.java:23)26at java.net.URLClassLoader.findClass(URLClassLoader.java:381)27at java.lang.ClassLoader.loadClass(ClassLoader.java:424)28at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
only
Using AI Code Generation
1package org.example;2import static org.mockito.Mockito.*;3import static org.junit.Assert.*;4import org.junit.Test;5import org.mockito.Mockito;6public class Test1 {7 public void test1() {8 MyClass test = Mockito.mock(MyClass.class);9 when(test.getUniqueId()).thenReturn(43);10 assertEquals(test.getUniqueId(), 43);11 }12}13package org.example;14import static org.mockito.Mockito.*;15import static org.junit.Assert.*;16import org.junit.Test;17import org.mockito.Mockito;18public class Test2 {19 public void test1() {20 MyClass test = Mockito.mock(MyClass.class);21 when(test.getUniqueId()).thenReturn(43);22 assertEquals(test.getUniqueId(), 43);23 }24}25package org.example;26import static org.mockito.Mockito.*;27import static org.junit.Assert.*;28import org.junit.Test;29import org.mockito.Mockito;30public class Test3 {31 public void test1() {32 MyClass test = Mockito.mock(MyClass.class);33 when(test.getUniqueId()).thenReturn(43);34 assertEquals(test.getUniqueId(), 43);35 }36}37package org.example;38import static org.mockito.Mockito.*;39import static org.junit.Assert.*;40import org.junit.Test;41import org.mockito.Mockito;42public class Test4 {43 public void test1() {44 MyClass test = Mockito.mock(MyClass.class);45 when(test.getUniqueId()).thenReturn(43);46 assertEquals(test.getUniqueId(), 43);47 }48}49package org.example;50import static org.mockito.Mockito.*;51import static org.junit.Assert.*;52import org.junit.Test;53import org.mockito.Mockito;54public class Test5 {
only
Using AI Code Generation
1import org.mockito.Mockito;2import static org.mockito.Mockito.*;3public class Test {4 public static void main(String[] args) {5 List mockedList = mock(List.class);6 when(mockedList.get(0)).thenReturn("first");7 when(mockedList.get(1)).thenThrow(new RuntimeException());8 System.out.println(mockedList.get(0));9 System.out.println(mockedList.get(1));10 System.out.println(mockedList.get(999));11 }12}13 at org.mockito.Mockito.mock(Mockito.java:1246)14 at Test.main(Test.java:8)15import org.mockito.Mockito;16import static org.mockito.Mockito.*;17public class Test {18 public static void main(String[] args) {19 List mockedList = mock(List.class);20 when(mockedList.get(0)).thenReturn("first");21 when(mockedList.get(1)).thenThrow(new RuntimeException());22 System.out.println(mockedList.get(0));23 System.out.println(mockedList.get(1));24 System.out.println(mockedList.get(999));25 }26}27 at org.mockito.Mockito.mock(Mockito.java:1246)28 at Test.main(Test.java:8)29import org.mockito.Mockito;30import static org.mockito.Mockito.*;31public class Test {32 public static void main(String[] args) {33 List mockedList = mock(List.class);34 when(mockedList.get(0)).thenReturn("first");35 when(mockedList.get(1)).thenThrow(new RuntimeException());36 System.out.println(mockedList.get(0));37 System.out.println(mockedList.get(1));
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!!