Best Mockito code snippet using org.mockito.Mockito.ignoreStubs
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 */...
Source:AoaTargetPreparerTest.java
...16package com.android.tradefed.targetprep;17import static org.mockito.ArgumentMatchers.any;18import static org.mockito.ArgumentMatchers.eq;19import static org.mockito.Mockito.doReturn;20import static org.mockito.Mockito.ignoreStubs;21import static org.mockito.Mockito.never;22import static org.mockito.Mockito.times;23import static org.mockito.Mockito.verify;24import static org.mockito.Mockito.verifyNoMoreInteractions;25import static org.mockito.Mockito.verifyZeroInteractions;26import static org.mockito.Mockito.when;27import com.android.helper.aoa.AoaDevice;28import com.android.helper.aoa.AoaKey;29import com.android.helper.aoa.UsbHelper;30import com.android.tradefed.build.IBuildInfo;31import com.android.tradefed.config.ConfigurationException;32import com.android.tradefed.config.OptionSetter;33import com.android.tradefed.device.DeviceNotAvailableException;34import com.android.tradefed.device.TestDevice;35import com.android.tradefed.invoker.IInvocationContext;36import com.android.tradefed.invoker.InvocationContext;37import com.android.tradefed.invoker.TestInformation;38import org.junit.Before;39import org.junit.Test;40import org.junit.runner.RunWith;41import org.mockito.Mock;42import org.mockito.Spy;43import org.mockito.junit.MockitoJUnitRunner;44import java.awt.Point;45import java.time.Duration;46import java.util.List;47/** Unit tests for {@link AoaTargetPreparer} */48@RunWith(MockitoJUnitRunner.class)49public class AoaTargetPreparerTest {50 @Spy private AoaTargetPreparer mPreparer;51 private OptionSetter mOptionSetter;52 @Mock private TestDevice mTestDevice;53 @Mock private IBuildInfo mBuildInfo;54 @Mock private UsbHelper mUsb;55 @Mock private AoaDevice mDevice;56 private TestInformation mTestInfo;57 @Before58 public void setUp() throws ConfigurationException {59 when(mUsb.getAoaDevice(any(), any())).thenReturn(mDevice);60 doReturn(mUsb).when(mPreparer).getUsbHelper();61 mOptionSetter = new OptionSetter(mPreparer);62 when(mDevice.getSerialNumber()).thenReturn("SERIAL");63 IInvocationContext context = new InvocationContext();64 context.addAllocatedDevice("device", mTestDevice);65 context.addDeviceBuildInfo("device", mBuildInfo);66 mTestInfo = TestInformation.newBuilder().setInvocationContext(context).build();67 }68 @Test69 public void testSetUp() throws Exception {70 mOptionSetter.setOptionValue("action", "wake");71 mOptionSetter.setOptionValue("device-timeout", "1s");72 mOptionSetter.setOptionValue("wait-for-device-online", "true");73 mPreparer.setUp(mTestInfo);74 // fetched device, executed actions, and verified status75 verify(mUsb).getAoaDevice(any(), eq(Duration.ofSeconds(1L)));76 verify(mPreparer).execute(eq(mDevice), eq("wake"));77 verify(mTestDevice).waitForDeviceOnline();78 }79 @Test80 public void testSetUp_noActions() throws Exception {81 mPreparer.setUp(mTestInfo);82 // no-op if no actions provided83 verifyZeroInteractions(mUsb);84 verify(mPreparer, never()).execute(eq(mDevice), any());85 verifyZeroInteractions(mTestDevice);86 }87 @Test(expected = DeviceNotAvailableException.class)88 public void testSetUp_noDevice() throws Exception {89 mOptionSetter.setOptionValue("action", "wake");90 when(mUsb.getAoaDevice(any(), any())).thenReturn(null); // device not found or incompatible91 mPreparer.setUp(mTestInfo);92 }93 @Test94 public void testSetUp_skipDeviceCheck() throws Exception {95 mOptionSetter.setOptionValue("action", "wake");96 mOptionSetter.setOptionValue("wait-for-device-online", "false"); // device check disabled97 mPreparer.setUp(mTestInfo);98 // actions executed, but status check skipped99 verify(mPreparer).execute(eq(mDevice), eq("wake"));100 verify(mTestDevice, never()).waitForDeviceOnline();101 }102 @Test103 public void testClick() {104 mPreparer.execute(mDevice, "click 1 23");105 verify(mDevice).click(eq(new Point(1, 23)));106 verifyNoMoreInteractions(ignoreStubs(mDevice));107 }108 @Test109 public void testLongClick() {110 mPreparer.execute(mDevice, "longClick 23 4");111 verify(mDevice).longClick(eq(new Point(23, 4)));112 verifyNoMoreInteractions(ignoreStubs(mDevice));113 }114 @Test115 public void testSwipe() {116 mPreparer.execute(mDevice, "swipe 3 45 123 6 78");117 verify(mDevice)118 .swipe(eq(new Point(3, 45)), eq(new Point(6, 78)), eq(Duration.ofMillis(123)));119 verifyNoMoreInteractions(ignoreStubs(mDevice));120 }121 @Test122 public void testWrite() {123 mPreparer.execute(mDevice, "write Abc 0123");124 verify(mDevice).pressKeys(List.of(125 new AoaKey(0x04, AoaKey.Modifier.SHIFT), new AoaKey(0x05), new AoaKey(0x06),126 new AoaKey(0x2C),127 new AoaKey(0x27), new AoaKey(0x1E), new AoaKey(0x1F), new AoaKey(0x20)));128 verifyNoMoreInteractions(ignoreStubs(mDevice));129 }130 @Test131 public void testKeys() {132 mPreparer.execute(mDevice, "key 43"); // accepts decimal values133 mPreparer.execute(mDevice, "key 0x2B"); // accepts hexadecimal values134 mPreparer.execute(mDevice, "key tab"); // accepts key descriptions135 verify(mDevice, times(3)).pressKeys(List.of(new AoaKey(0x2B)));136 verifyNoMoreInteractions(ignoreStubs(mDevice));137 }138 @Test139 public void testKeys_combination() {140 mPreparer.execute(mDevice, "key 2*A 3*down 2*0x2B");141 verify(mDevice).pressKeys(List.of(142 new AoaKey(0x04, AoaKey.Modifier.SHIFT), new AoaKey(0x04, AoaKey.Modifier.SHIFT),143 new AoaKey(0x51), new AoaKey(0x51), new AoaKey(0x51),144 new AoaKey(0x2B), new AoaKey(0x2B)));145 verifyNoMoreInteractions(ignoreStubs(mDevice));146 }147 @Test148 public void testWake() {149 mPreparer.execute(mDevice, "wake");150 verify(mDevice).wakeUp();151 verifyNoMoreInteractions(ignoreStubs(mDevice));152 }153 @Test154 public void testHome() {155 mPreparer.execute(mDevice, "home");156 verify(mDevice).goHome();157 verifyNoMoreInteractions(ignoreStubs(mDevice));158 }159 @Test160 public void testBack() {161 mPreparer.execute(mDevice, "back");162 verify(mDevice).goBack();163 verifyNoMoreInteractions(ignoreStubs(mDevice));164 }165 @Test166 public void testSleep() {167 mPreparer.execute(mDevice, "sleep 123");168 verify(mDevice).sleep(eq(Duration.ofMillis(123L)));169 verifyNoMoreInteractions(ignoreStubs(mDevice));170 }171 @Test(expected = IllegalArgumentException.class)172 public void testInvalid_unknownKeyword() {173 mPreparer.execute(mDevice, "jump 12 3");174 }175 @Test(expected = IllegalArgumentException.class)176 public void testInvalid_missingCoordinates() {177 mPreparer.execute(mDevice, "click");178 }179 @Test(expected = IllegalArgumentException.class)180 public void testInvalid_tooFewCoordinates() {181 mPreparer.execute(mDevice, "longClick 1");182 }183 @Test(expected = IllegalArgumentException.class)...
Source:LibrettoControllerTest.java
1package com.example.libretto.controller;2import static org.mockito.Mockito.doThrow;3import static org.mockito.Mockito.ignoreStubs;4import static org.mockito.Mockito.inOrder;5import static org.mockito.Mockito.verify;6import static org.mockito.Mockito.verifyNoMoreInteractions;7import static org.mockito.Mockito.when;8import static java.util.Arrays.asList;9import java.sql.SQLException;10import java.time.LocalDate;11import java.util.List;12import org.junit.jupiter.api.DisplayName;13import org.junit.jupiter.api.Nested;14import org.junit.jupiter.api.Test;15import org.junit.jupiter.api.extension.ExtendWith;16import org.mockito.InOrder;17import org.mockito.InjectMocks;18import org.mockito.Mock;19import org.mockito.junit.jupiter.MockitoExtension;20import com.example.libretto.model.Exam;21import com.example.libretto.model.Grade;22import com.example.libretto.repository.ExamRepository;23import com.example.libretto.view.LibrettoView;24@ExtendWith(MockitoExtension.class)25@DisplayName("Tests for Libretto Controller")26class LibrettoControllerTest {27 28 @Mock29 private ExamRepository examRepository;30 @Mock31 private LibrettoView librettoView;32 @InjectMocks33 private LibrettoController librettoController;34 35 @Nested36 @DisplayName("All exams")37 class AllExams {38 @Test @DisplayName("Happy case")39 void testAllExams() throws SQLException {40 LocalDate examDate = LocalDate.of(2020, 1, 29);41 Grade grade = new Grade("30");42 Exam exam = new Exam("B027500", "Data Mining and Organization", 12, grade, examDate);43 44 List<Exam> exams = asList(exam);45 when(examRepository.findAll()).thenReturn(exams);46 librettoController.allExams();47 verify(librettoView).showAllExams(exams);48 }49 @Test @DisplayName("Throws SQL Exception")50 void testAllExamsThrows() throws SQLException {51 when(examRepository.findAll()).thenThrow(SQLException.class);52 librettoController.allExams();53 verify(librettoView).showError("Errore SQL");54 }55 }56 @Nested57 @DisplayName("New exam")58 class NewExam {59 @Test @DisplayName("When exists")60 void testNewExamWhenExists() throws SQLException {61 LocalDate examDate1 = LocalDate.of(2020, 1, 29);62 Grade grade1 = new Grade("30");63 Exam examToAdd = new Exam("B027500", "Data Mining and Organization", 12, grade1, examDate1);64 65 LocalDate examDate2 = LocalDate.of(2020, 1, 29);66 Grade grade2 = new Grade("28");67 Exam existingExam = new Exam("B027500", "Parallel Computing", 6, grade2, examDate2);68 69 when(examRepository.findById("B027500")).thenReturn(existingExam);70 librettoController.newExam(examToAdd);71 verify(librettoView).showErrorExamAlreadyExists("Esame già presente con codice B027500", existingExam);72 verifyNoMoreInteractions(ignoreStubs(examRepository));73 }74 @Test @DisplayName("When not exists")75 void testNewExamWhenDoesNotExists() throws SQLException {76 LocalDate examDate = LocalDate.of(2020, 1, 29);77 Grade grade = new Grade("30");78 Exam exam = new Exam("B027500", "Data Mining and Organization", 12, grade, examDate);79 librettoController.newExam(exam);80 InOrder inOrder = inOrder(examRepository, librettoView);81 inOrder.verify(examRepository).save(exam);82 inOrder.verify(librettoView).examAdded(exam);83 }84 85 @Test @DisplayName("Throws SQL Exception")86 void testNewExamsThrows() throws SQLException {87 LocalDate examDate = LocalDate.of(2020, 1, 29);88 Grade grade = new Grade("30");89 Exam exam = new Exam("B027500", "Data Mining and Organization", 12, grade, examDate);90 doThrow(SQLException.class).when(examRepository).save(exam);91 librettoController.newExam(exam);92 verify(librettoView).showError("Errore SQL");93 }94 }95 @Nested96 @DisplayName("Update exam")97 class UpdateExam {98 @Test @DisplayName("When exists")99 void testUpdateExamWhenExists() throws SQLException {100 LocalDate examDate = LocalDate.of(2020, 1, 29);101 Grade grade = new Grade("30");102 Exam examToUpdate = new Exam("B027500", "Data Mining and Organization", 12, grade, examDate);103 Exam examUpdated = new Exam("B027500", "Data Science", 6, grade, examDate);104 when(examRepository.findById("B027500")).thenReturn(examToUpdate);105 librettoController.updateExam(examUpdated);106 InOrder inOrder = inOrder(examRepository, librettoView);107 inOrder.verify(librettoView).examRemoved(examToUpdate);108 inOrder.verify(examRepository).update(examUpdated);109 inOrder.verify(librettoView).examAdded(examUpdated);110 }111 112 @Test @DisplayName("When not exists")113 void testUpdateExamWhenDoesNotExists() throws SQLException {114 LocalDate examDate = LocalDate.of(2020, 1, 29);115 Grade grade = new Grade("30");116 Exam exam = new Exam("B027500", "Data Mining and Organization", 12, grade, examDate);117 when(examRepository.findById("B027500")).thenReturn(null);118 librettoController.updateExam(exam);119 verify(librettoView).showErrorExamNotFound("Esame inesistente con codice B027500", exam);120 verifyNoMoreInteractions(ignoreStubs(examRepository)); 121 }122 123 @Test @DisplayName("Throws SQL Exception")124 void testUpdateExamsThrows() throws SQLException {125 LocalDate examDate = LocalDate.of(2020, 1, 29);126 Grade grade = new Grade("30");127 Exam exam = new Exam("B027500", "Data Mining and Organization", 12, grade, examDate);128 when(examRepository.findById("B027500")).thenReturn(exam);129 doThrow(SQLException.class).when(examRepository).update(exam);130 librettoController.updateExam(exam);131 verify(librettoView).showError("Errore SQL");132 }133 }134 @Nested135 @DisplayName("Delete exam")136 class DeleteExam {137 @Test @DisplayName("When exists")138 void testDeleteExamWhenExists() throws SQLException {139 LocalDate examDate = LocalDate.of(2020, 1, 29);140 Grade grade = new Grade("30");141 Exam examToDelete = new Exam("B027500", "Data Mining and Organization", 12, grade, examDate);142 when(examRepository.findById("B027500")).thenReturn(examToDelete);143 librettoController.deleteExam(examToDelete);144 InOrder inOrder = inOrder(examRepository, librettoView);145 inOrder.verify(examRepository).delete("B027500");146 inOrder.verify(librettoView).examRemoved(examToDelete);147 }148 @Test @DisplayName("When not exists")149 void testDeleteExamWhenDoesNotExists() throws SQLException {150 LocalDate examDate = LocalDate.of(2020, 1, 29);151 Grade grade = new Grade("30");152 Exam exam = new Exam("B027500", "Data Mining and Organization", 12, grade, examDate);153 when(examRepository.findById("B027500")).thenReturn(null);154 librettoController.deleteExam(exam);155 verify(librettoView).showErrorExamNotFound("Esame inesistente con codice B027500", exam);156 verifyNoMoreInteractions(ignoreStubs(examRepository)); 157 }158 @Test @DisplayName("Throws SQL Exception")159 void testDeleteExamThrows() throws SQLException {160 LocalDate examDate = LocalDate.of(2020, 1, 29);161 Grade grade = new Grade("30");162 Exam examToDelete = new Exam("B027500", "Data Mining and Organization", 12, grade, examDate);163 when(examRepository.findById("B027500")).thenReturn(examToDelete);164 doThrow(SQLException.class).when(examRepository).delete("B027500");165 librettoController.deleteExam(examToDelete);166 verify(librettoView).showError("Errore SQL");167 }168 }169}...
Source:ShopControllerTest.java
...36 Item item = new Item(PRODUCT_CODE, ITEM_NAME, -1);37 when(shopRepository.findItemByProductCode(PRODUCT_CODE)).thenReturn(null);38 assertThatThrownBy(() -> shopController.newItem(item)).isInstanceOf(IllegalArgumentException.class)39 .hasMessage("Negative amount: -1");40 verifyNoMoreInteractions(ignoreStubs(shopRepository));41 }42 @Test43 public void testNewItemWhenQuantityIsZero() {44 Item item = new Item(PRODUCT_CODE, ITEM_NAME, 0);45 when(shopRepository.findItemByProductCode(PRODUCT_CODE)).thenReturn(null);46 assertThatThrownBy(() -> shopController.newItem(item)).isInstanceOf(IllegalArgumentException.class)47 .hasMessage("Negative amount: 0");48 verifyNoMoreInteractions(ignoreStubs(shopRepository));49 }50 @Test51 public void testNewItemWhenItemDoesNotAlreadyExists() {52 Item item = new Item(PRODUCT_CODE, ITEM_NAME);53 when(shopRepository.findItemByProductCode(PRODUCT_CODE)).thenReturn(null);54 shopController.newItem(item);55 InOrder inOrder = inOrder(shopRepository, shopView);56 inOrder.verify(shopRepository).storeItem(item);57 }58 @Test59 public void testNewItemWhenItemAlreadyExists() {60 Item itemToAdd = new Item(PRODUCT_CODE, ITEM_NAME, 1);61 Item existingItem = new Item(PRODUCT_CODE, ITEM_NAME, 2);62 when(shopRepository.findItemByProductCode(PRODUCT_CODE)).thenReturn(existingItem);63 shopController.newItem(itemToAdd);64 InOrder inOrder = inOrder(shopRepository, shopView);65 inOrder.verify(shopRepository).modifyItemQuantity(existingItem, 1);66 }67 @Test68 public void testRemoveItemWhenItemAlreadyExists() {69 Item itemToRemove = new Item(PRODUCT_CODE, ITEM_NAME);70 when(shopRepository.findItemByProductCode(PRODUCT_CODE)).thenReturn(itemToRemove);71 shopController.removeItem(itemToRemove);72 InOrder inOrder = inOrder(shopRepository, shopView);73 inOrder.verify(shopRepository).removeItem(PRODUCT_CODE);74 }75 @Test76 public void testRemoveItemWhenItemDoesNotAlreadyExists() {77 Item itemToRemove = new Item(PRODUCT_CODE, ITEM_NAME);78 when(shopRepository.findItemByProductCode(PRODUCT_CODE)).thenReturn(null);79 shopController.removeItem(itemToRemove);80 verifyNoMoreInteractions(ignoreStubs(shopRepository));81 }82 @Test83 public void testSearchItemWhenTextBoxIsEmpty() {84 when(shopRepository.findItemByName("")).thenReturn(null);85 shopController.searchItem("");86 verify(shopView).updateItemsShop(shopRepository.findAllItems());87 verifyNoMoreInteractions(ignoreStubs(shopView));88 }89 @Test90 public void testSearchItemWhenItemAlreadyExists() {91 Item itemToSearch = new Item("1", ITEM_NAME);92 when(shopRepository.findItemByName(ITEM_NAME)).thenReturn(itemToSearch);93 shopController.searchItem(itemToSearch.getName());94 verify(shopView).showSearchResult(itemToSearch);95 }96 @Test97 public void testSearchItemWhenItemDoestNotExists() {98 when(shopRepository.findItemByName(ITEM_NAME)).thenReturn(null);99 shopController.searchItem(ITEM_NAME);100 verify(shopView).errorLogItem("Item with name does not exists", ITEM_NAME);101 verifyNoMoreInteractions(ignoreStubs(shopRepository));102 }103 @Test104 public void testModifyQuantityWhenModifierIsLessThanItemQuantity() {105 Item itemToModify = new Item(PRODUCT_CODE, ITEM_NAME, 2);106 shopController.modifyItemQuantity(itemToModify, -1);107 verify(shopRepository).modifyItemQuantity(itemToModify, -1);108 }109 @Test110 public void testModifyQuantityWhenModifierIsEqualToItemQuantity() {111 Item itemToModify = new Item(PRODUCT_CODE, ITEM_NAME, 2);112 shopController.modifyItemQuantity(itemToModify, -2);113 verify(shopRepository).removeItem(itemToModify.getProductCode());114 verifyNoMoreInteractions(ignoreStubs(shopRepository));115 }116 @Test117 public void testModifyQuantityWhenModifierIsZero() {118 Item itemToModify = new Item(PRODUCT_CODE, ITEM_NAME, 2);119 shopController.modifyItemQuantity(itemToModify, 0);120 verifyNoMoreInteractions(ignoreStubs(shopRepository));121 }122 @Test123 public void testModifyQuantityWhenModifierIsGreaterThanItemQuantity() {124 Item itemToModify = new Item(PRODUCT_CODE, ITEM_NAME, 2);125 shopController.modifyItemQuantity(itemToModify, -3);126 verifyNoMoreInteractions(ignoreStubs(shopRepository));127 }128}...
Source:LibraryControllerTest.java
...72 libraryController.newLibrary(library);73 74 // verify75 verify(libraryView).showError("Already existing library with id 1", library);76 verifyNoMoreInteractions(ignoreStubs(libraryRepository));77 }78 79 @Test80 public void testNewLibraryWhenIdIsEmptyShouldThrow() {81 // setup82 Library library = new Library("", "library1");83 84 // exercise & verify85 assertThatThrownBy(() -> libraryController.newLibrary(library))86 .isInstanceOf(IllegalArgumentException.class)87 .hasMessage("Id library cannot be empty or only blank space");88 verifyNoMoreInteractions(ignoreStubs(libraryRepository));89 }90 91 @Test92 public void testNewLibraryWhenIdAreOnlyBlankSpaceShouldThrow() {93 // setup94 Library library = new Library(" ", "library1");95 96 // exercise & verify97 assertThatThrownBy(() -> libraryController.newLibrary(library))98 .isInstanceOf(IllegalArgumentException.class)99 .hasMessage("Id library cannot be empty or only blank space");100 verifyNoMoreInteractions(ignoreStubs(libraryRepository));101 }102 103 @Test104 public void testDeleteLibraryWhenLibraryExist() {105 // setup106 Library library = new Library("1", "library1");107 when(libraryRepository.findLibraryById("1")).thenReturn(library);108 109 // exercise110 libraryController.deleteLibrary(library);111 112 // verify113 InOrder inOrder = inOrder(libraryRepository, libraryView);114 inOrder.verify(libraryRepository).deleteLibrary("1");115 inOrder.verify(libraryView).libraryRemoved(library);116 }117 118 @Test119 public void testDeleteLibraryWhenLibraryDoesntExist() {120 // setup121 Library library = new Library("1", "library1");122 when(libraryRepository.findLibraryById("1")).thenReturn(null);123 124 // exercise125 libraryController.deleteLibrary(library);126 127 // verify128 verify(libraryView).libraryRemoved(library);129 verify(libraryView).showError("Doesn't exist library with id 1", library);130 verifyNoMoreInteractions(ignoreStubs(libraryRepository));131 }132 133 @Test134 public void testFindLibraryWhenLibraryExist() {135 // setup136 Library library = new Library("1", "library1");137 when(libraryRepository.findLibraryById("1")).thenReturn(library);138 139 // exercise140 libraryController.findLibrary(library);141 142 // verify143 InOrder inOrder = inOrder(libraryRepository, libraryView);144 inOrder.verify(libraryRepository).findLibraryById("1");145 inOrder.verify(libraryView).showAllBooksOfLibrary(library);146 }147 148 @Test149 public void testFindLibraryWhenLibraryDoesntExist() {150 // setup151 Library library = new Library("1", "library1");152 when(libraryRepository.findLibraryById("1")).thenReturn(null);153 154 // exercise155 libraryController.findLibrary(library);156 157 // verify158 InOrder inOrder = inOrder(libraryRepository, libraryView);159 inOrder.verify(libraryRepository).findLibraryById("1");160 inOrder.verify(libraryView).libraryRemoved(library);161 inOrder.verify(libraryView).showError("Doesn't exist library with id 1", library);162 verifyNoMoreInteractions(ignoreStubs(libraryRepository));163 }164}...
Source:NoMoreInteractionsExcludingStubsTest.java
...30 //verifyNoMoreInteractions fails:31 try { verifyNoMoreInteractions(mock); fail(); } catch (NoInteractionsWanted e) {};32 33 //but it works when stubs are ignored:34 ignoreStubs(mock);35 verifyNoMoreInteractions(mock);36 }37// @Test38// public void shouldIgnoringStubsDetectNulls() throws Exception {39// //given40//41// //when42// ignoreStubs(mock, null);43//44// //then45// }46//47// @Test48// public void shouldIgnoringStubsDetectNonMocks() throws Exception {49// //given50//51// //when52// ignoreStubs(mock, new Object());53//54// //then55// }56 /**57 * Ignores stubbed methods of given mocks for the sake of verification.58 * <p>59 * Other words: all *stubbed* methods of given mocks are made *verfied* so that they don't get in a way during verifyNoMoreInteractions().60 * <p>61 * This method changes the input mocks! This method returns input mocks for convenience. 62 * <p>63 * Example:64 * <pre>65 * //mocking lists for the sake of the example (if you mock List in real you will burn in hell)66 * List mock1 = mock(List.class), mock2 = mock(List.class);67 * 68 * //stubbing mocks:69 * when(mock1.get(0)).thenReturn(10);70 * when(mock2.get(0)).thenReturn(20);71 *72 * //using mocks by calling stubbed get(0) methods:73 * System.out.println(mock1.get(0)); //prints 1074 * System.out.println(mock2.get(0)); //prints 2075 *76 * //using mocks by calling clear() methods:77 * mock1.clear();78 * mock2.clear();79 *80 * //verification:81 * verify(mock1).clear();82 * verify(mock2).clear();83 *84 * //verifyNoMoreInteractions() fails because get() methods were not accounted for.85 * try { verifyNoMoreInteractions(mock1, mock2); } catch (NoInteractionsWanted e);86 *87 * //However, if ignore stubbed methods then we can verifyNoMoreInteractions() 88 * verifyNoMoreInteractions(ignoreStubs(mock1, mock2));89 *90 * //Remember that ignoreStubs() *changes* the input mocks and returns them for convenience.91 * <pre>92 *93 * @param mocks input mocks that will be changed94 * @return the same mocks that were passed in as parameters95 */96 public static Object[] ignoreStubs(Object... mocks) {97 for (Object m : mocks) {98 InvocationContainer invocationContainer = new MockUtil().getMockHandler(m).getInvocationContainer();99 List<Invocation> ins = invocationContainer.getInvocations();100 for (Invocation in : ins) {101 InvocationMarker invocationMarker = new InvocationMarker();102 if (in.stubInfo() != null) {103 invocationMarker.markVerified(in, new CapturesArgumensFromInvocation() {104 public void captureArgumentsFrom(Invocation i) {105 //don't capture106 }107 });108 }109 }110 }...
Source:SchoolControllerTest.java
1package com.example.school.controller;2import static java.util.Arrays.asList;3import static org.mockito.Mockito.ignoreStubs;4import static org.mockito.Mockito.verify;5import static org.mockito.Mockito.verifyNoMoreInteractions;6import static org.mockito.Mockito.when;7import java.util.List;8import org.junit.jupiter.api.Test;9import org.junit.jupiter.api.extension.ExtendWith;10import org.mockito.InOrder;11import org.mockito.InjectMocks;12import org.mockito.Mock;13import org.mockito.Mockito;14import org.mockito.junit.jupiter.MockitoExtension;15import com.example.school.model.Student;16import com.example.school.repository.StudentRepository;17import com.example.school.view.StudentView;18@ExtendWith(MockitoExtension.class)19class SchoolControllerTest {20 @Mock21 private StudentRepository studentRepository;22 @Mock23 private StudentView studentView;24 @InjectMocks25 private SchoolController schoolController;26 @Test27 void testAllStudents() {28 List<Student> students = asList(new Student());29 when(studentRepository.findAll()).thenReturn(students);30 schoolController.allStudents();31 verify(studentView).showAllStudents(students);32 }33 @Test34 void testNewStudentWhenStudentDoesNotAlreadyExist() {35 Student student = new Student("1", "test");36 when(studentRepository.findById("1")).thenReturn(null);37 schoolController.newStudent(student);38 InOrder inOrder = Mockito.inOrder(studentRepository, studentView);39 inOrder.verify(studentRepository).save(student);40 inOrder.verify(studentView).studentAdded(student);41 verifyNoMoreInteractions(ignoreStubs(studentRepository));42 }43 @Test44 void testNewStudentWhenStudentAlreadyExists() {45 Student studentToAdd = new Student("1", "test");46 Student existingStudent = new Student("1", "name");47 when(studentRepository.findById("1")).thenReturn(existingStudent);48 schoolController.newStudent(studentToAdd);49 verify(studentView).showError("Already existing student with id 1", existingStudent);50 verifyNoMoreInteractions(ignoreStubs(studentRepository));51 }52 @Test53 void testDeleteStudentWhenStudentExists() {54 Student studentToDelete = new Student("1", "test");55 when(studentRepository.findById("1")).thenReturn(studentToDelete);56 schoolController.deleteStudent(studentToDelete);57 InOrder inOrder = Mockito.inOrder(studentRepository, studentView);58 inOrder.verify(studentRepository).delete("1");59 inOrder.verify(studentView).studentRemoved(studentToDelete);60 verifyNoMoreInteractions(ignoreStubs(studentRepository));61 }62 @Test63 void testDeleteStudentWhenStudentDoesNotExist() {64 Student studentToDelete = new Student("1", "test");65 when(studentRepository.findById("1")).thenReturn(null);66 schoolController.deleteStudent(studentToDelete);67 verify(studentView).showError("No existing student with id 1", studentToDelete);68 verifyNoMoreInteractions(ignoreStubs(studentRepository));69 }70}...
Source:VerificationExcludingStubsTest.java
...26 //verifyNoMoreInteractions fails:27 try { verifyNoMoreInteractions(mock); fail(); } catch (NoInteractionsWanted e) {};28 29 //but it works when stubs are ignored:30 ignoreStubs(mock);31 verifyNoMoreInteractions(mock);32 }33 @Test34 public void shouldExcludeFromVerificationInOrder() throws Exception {35 //given36 when(mock.simpleMethod()).thenReturn("foo");37 //when38 mock.objectArgMethod("1");39 mock.objectArgMethod("2");40 mock.simpleMethod(); //calling the stub41 //then42 InOrder inOrder = inOrder(ignoreStubs(mock));43 inOrder.verify(mock).objectArgMethod("1");44 inOrder.verify(mock).objectArgMethod("2");45 inOrder.verifyNoMoreInteractions();46 verifyNoMoreInteractions(mock);47 }48 @Test(expected = NotAMockException.class)49 public void shouldIgnoringStubsDetectNulls() throws Exception {50 ignoreStubs(mock, null);51 }52 @Test(expected = NotAMockException.class)53 public void shouldIgnoringStubsDetectNonMocks() throws Exception {54 ignoreStubs(mock, new Object());55 }56}...
ignoreStubs
Using AI Code Generation
1package org.mockito;2import static org.mockito.Mockito.*;3import org.mockito.exceptions.base.MockitoException;4import org.mockito.internal.stubbing.answers.ThrowsException;5import org.mockito.invocation.InvocationOnMock;6import org.mockito.stubbing.Answer;7import java.util.*;8public class MockitoDemo {9 public static void main(String[] args) {10 List mock = mock(List.class);11 when(mock.get(0)).thenReturn("Hello");12 when(mock.get(1)).thenThrow(new RuntimeException());13 when(mock.get(2)).thenAnswer(new Answer() {14 public Object answer(InvocationOnMock invocation) throws Throwable {15 return "called with arguments: " + Arrays.toString(invocation.getArguments());16 }17 });18 System.out.println(mock.get(0));19 try {20 mock.get(1);21 } catch (RuntimeException e) {22 System.out.println("Exception occured");23 }24 System.out.println(mock.get(2));25 mock.get(3);26 Mockito.ignoreStubs(mock);27 System.out.println(mock.get(3));28 }29}
ignoreStubs
Using AI Code Generation
1package org.mockito;2import static 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}12-> at 1.main(1.java:18)13-> at 1.main(1.java:17)14-> at 1.main(1.java:16)
ignoreStubs
Using AI Code Generation
1import org.mockito.Mockito;2{3 public static void main(String[] args)4 {5 List mockList = Mockito.mock(List.class);6 Mockito.ignoreStubs(mockList);7 }8}
ignoreStubs
Using AI Code Generation
1package org.mockito;2import org.mockito.internal.stubbing.answers.ThrowsException;3import org.mockito.stubbing.Answer;4import org.mockito.stubbing.Stubber;5import org.mockito.stubbing.VoidAnswer1;6import org.mockito.stubbing.VoidAnswer2;7import org.mockito.stubbing.VoidAnswer3;8import org.mockito.stubbing.VoidAnswer4;9import org.mockito.stubbing.VoidAnswer5;10import org.mockito.stubbing.VoidAnswer6;11import org.mockito.stubbing.VoidAnswer7;12import org.mockito.stubbing.VoidAnswer8;13import org.mockito.stubbing.VoidAnswer9;14import org.mockito.stubbing.VoidAnswer10;15import org.mockito.stubbing.VoidAnswer11;16import org.mockito.stubbing.VoidAnswer12;17import org.mockito.stubbing.VoidAnswer13;18import org.mockito.stubbing.VoidAnswer14;19import org.mockito.stubbing.VoidAnswer15;20import org.mockito.stubbing.VoidAnswer16;21import org.mockito.stubbing.VoidAnswer17;22import org.mockito.stubbing.VoidAnswer18;23import org.mockito.stubbing.VoidAnswer19;24import org.mockito.stubbing.VoidAnswer20;25import org.mockito.stubbing.VoidAnswer21;26import org.mockito.stubbing.VoidAnswer22;27import org.mockito.stubbing.VoidAnswer23;28import org.mockito.stubbing.VoidAnswer24;29import org.mockito.stubbing.VoidAnswer25;30import org.mockito.stubbing.VoidAnswer26;31import org.mockito.stubbing.VoidAnswer27;32import org.mockito.stubbing.VoidAnswer28;33import org.mockito.stubbing.VoidAnswer29;34import org.mockito.stubbing.VoidAnswer30;35import org.mockito.stubbing.VoidAnswer31;36import org.mockito.stubbing.VoidAnswer32;37import org.mockito.stubbing.VoidAnswer33;38import org.mockito.stubbing.VoidAnswer34;39import org.mockito.stubbing.VoidAnswer35;40import org.mockito.stubbing.VoidAnswer36;41import org.mockito.stubbing.VoidAnswer37;42import org.mockito.stubbing.VoidAnswer38;43import org.mockito.stubbing.VoidAnswer39;44import org.mockito.stubbing.VoidAnswer40;45import org.mockito.stubbing.VoidAnswer41;46import org.mockito.stubbing.VoidAnswer42;47import org.mockito.stubbing.VoidAnswer43;48import org.mockito.stubbing.VoidAnswer44;49import org.mockito.stubbing.VoidAnswer45;50import org.mockito.stubbing.VoidAnswer46;51import org.mockito.stubbing.VoidAnswer47;52import org.mockito.stubbing.VoidAnswer48;53import org.mockito.stubbing.VoidAnswer49;54import org.mockito.stubbing.VoidAnswer50;55import org.mockito.stubbing.VoidAnswer51;56import org.mockito.stubbing.VoidAnswer52;
ignoreStubs
Using AI Code Generation
1package org.mockito;2import static org.mockito.Mockito.*;3public class 1 {4 public static void main(String[] args) {5 List mockList = mock(List.class);6 when(mockList.get(0)).thenReturn("Mockito");7 mockList.add("In28Minutes");8 verify(mockList).add("In28Minutes");9 verify(mockList, never()).clear();10 when(mockList.get(0)).thenReturn("Mockito");11 mockList.add("In28Minutes");12 verify(mockList, ignoreStubs()).add("In28Minutes");13 verify(mockList, never()).clear();14 }15}16Following stubbings are unnecessary (click to navigate to relevant line of code):171. -> at 1.main(1.java:0)18at org.mockito.exceptions.misusing.UnnecessaryStubbingException.create(UnnecessaryStubbingException.java:53)19at org.mockito.internal.stubbing.StubbedInvocationMatcher.reportStubbing(StubbedInvocationMatcher.java:61)20at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:93)21at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)22at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38)23at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:45)24at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:24)25at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptSuperCallable(MockMethodInterceptor.java:100)26at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptSuperCallable(MockMethodInterceptor.java:92)27at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.intercept(MockMethodInterceptor.java:79)28at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.intercept(MockMethodInterceptor.java:62)
ignoreStubs
Using AI Code Generation
1import org.mockito.Mockito;2public class MockitoExample {3 public static void main(String[] args) {4 Object object = Mockito.mock(Object.class);5 Mockito.ignoreStubs(object);6 }7}
ignoreStubs
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.stubbing.OngoingStubbing;3import org.mockito.stubbing.Stubber;4public class 1 {5 public static void main(String[] args) {6 Stubber stubber = Mockito.ignoreStubs();7 OngoingStubbing<String> stubbing = stubber.when("Hello");8 stubbing.thenReturn("Hi");9 System.out.println("Stubbed value: " + stubbing.thenReturn("Hi"));10 }11}
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!!