How to use ArgumentMatchers class of org.mockito package

Best Mockito code snippet using org.mockito.ArgumentMatchers

Source:AlertRepositoryTest.java Github

copy

Full Screen

...59 matrixCursor.addRow(alertRow);60 when(repository.getReadableDatabase()).thenReturn(sqliteDatabase);61 when(repository.getWritableDatabase()).thenReturn(sqliteDatabase);62 alertRepository.updateMasterRepository(repository);63 Mockito.when(sqliteDatabase.query(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.isNull(String[].class), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.isNull(String.class))).thenReturn(matrixCursor);64 Assert.assertNotNull(alertRepository.allAlerts());65 }66 @Test67 public void createAlertsCallsInsert1TimeForNewALerts() throws Exception {68 MatrixCursor matrixCursor = new MatrixCursor(alertColumns);69// matrixCursor.addRow(alertRow);70 when(repository.getReadableDatabase()).thenReturn(sqliteDatabase);71 when(repository.getWritableDatabase()).thenReturn(sqliteDatabase);72 alertRepository.updateMasterRepository(repository);73 Mockito.when(sqliteDatabase.query(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.isNull(String.class))).thenReturn(matrixCursor);74 Alert alert = new Alert("caseID", "scheduleName", "visitCode", AlertStatus.urgent, "startDate", "expiryDate", true);75 alertRepository.createAlert(alert);76 Mockito.verify(sqliteDatabase, Mockito.times(1)).insert(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.any(ContentValues.class));77 }78 @Test79 public void createAlertsCallsUpdate1TimeForOldALerts() throws Exception {80 MatrixCursor matrixCursor = new MatrixCursor(alertColumns);81 matrixCursor.addRow(alertRow);82 when(repository.getReadableDatabase()).thenReturn(sqliteDatabase);83 when(repository.getWritableDatabase()).thenReturn(sqliteDatabase);84 alertRepository.updateMasterRepository(repository);85 Mockito.when(sqliteDatabase.query(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.isNull(String.class))).thenReturn(matrixCursor);86 Alert alert = new Alert("caseID", "scheduleName", "visitCode", AlertStatus.urgent, "startDate", "expiryDate", true);87 alertRepository.createAlert(alert);88 Mockito.verify(sqliteDatabase, Mockito.times(1)).update(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(ContentValues.class), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class));89 }90 @Test91 public void changeAlertStatusToInProcess1CallsUpdate1Time() throws Exception {92 MatrixCursor matrixCursor = new MatrixCursor(alertColumns);93 matrixCursor.addRow(alertRow);94 when(repository.getReadableDatabase()).thenReturn(sqliteDatabase);95 when(repository.getWritableDatabase()).thenReturn(sqliteDatabase);96 alertRepository.updateMasterRepository(repository);97 alertRepository.changeAlertStatusToInProcess("caseID", "scheduleName");98 Mockito.verify(sqliteDatabase, Mockito.times(1)).update(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(ContentValues.class), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class));99 }100 @Test101 public void changeAlertStatusToCompleteCallsUpdate1Time() throws Exception {102 MatrixCursor matrixCursor = new MatrixCursor(alertColumns);103 matrixCursor.addRow(alertRow);104 when(repository.getReadableDatabase()).thenReturn(sqliteDatabase);105 when(repository.getWritableDatabase()).thenReturn(sqliteDatabase);106 alertRepository.updateMasterRepository(repository);107 alertRepository.changeAlertStatusToComplete("caseID", "scheduleName");108 Mockito.verify(sqliteDatabase, Mockito.times(1)).update(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(ContentValues.class), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class));109 }110 @Test111 public void markAlertAsClosedCallsUpdate1Time() throws Exception {112 MatrixCursor matrixCursor = new MatrixCursor(alertColumns);113 matrixCursor.addRow(alertRow);114 when(repository.getReadableDatabase()).thenReturn(sqliteDatabase);115 when(repository.getWritableDatabase()).thenReturn(sqliteDatabase);116 alertRepository.updateMasterRepository(repository);117 alertRepository.markAlertAsClosed("caseID", "scheduleName", "completionDate");118 Mockito.verify(sqliteDatabase, Mockito.times(1)).update(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(ContentValues.class), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class));119 }120 @Test121 public void filterActiveAlertsReturnsNotNull() throws Exception {122 MatrixCursor matrixCursor = new MatrixCursor(alertColumns);123 LocalDate today = LocalDate.now();124 today = today.plusDays(5);125 Object[] alertRowForActiveALerts = {"caseID", "scheduleName", "visitCode", "urgent", "", today.toString(), "", 1};126 matrixCursor.addRow(alertRowForActiveALerts);127 when(repository.getReadableDatabase()).thenReturn(sqliteDatabase);128 when(repository.getWritableDatabase()).thenReturn(sqliteDatabase);129 alertRepository.updateMasterRepository(repository);130 Mockito.when(sqliteDatabase.query(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.isNull(String.class))).thenReturn(matrixCursor);131 Assert.assertNotNull(alertRepository.allActiveAlertsForCase("caseID"));132 }133 @Test134 public void deleteAllAlertsForEntityCallsDelete1Times() throws Exception {135 when(repository.getReadableDatabase()).thenReturn(sqliteDatabase);136 when(repository.getWritableDatabase()).thenReturn(sqliteDatabase);137 alertRepository.updateMasterRepository(repository);138 alertRepository.deleteAllAlertsForEntity("caseID");139 Mockito.verify(sqliteDatabase, Mockito.times(1)).delete(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class));140 }141 @Test142 public void deleteAllOfflineAlertsForEntityCallsDelete1Times() throws Exception {143 when(repository.getReadableDatabase()).thenReturn(sqliteDatabase);144 when(repository.getWritableDatabase()).thenReturn(sqliteDatabase);145 alertRepository.updateMasterRepository(repository);146 alertRepository.deleteOfflineAlertsForEntity("caseID");147 Mockito.verify(sqliteDatabase, Mockito.times(1)).delete(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class));148 }149 @Test150 public void deleteAllOfflineAlertsForEntityAndNameCallsDelete1Times() throws Exception {151 when(repository.getReadableDatabase()).thenReturn(sqliteDatabase);152 when(repository.getWritableDatabase()).thenReturn(sqliteDatabase);153 alertRepository.updateMasterRepository(repository);154 alertRepository.deleteOfflineAlertsForEntity("caseID", "name1", "name2");155 Mockito.verify(sqliteDatabase, Mockito.times(1)).delete(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class));156 }157 @Test158 public void deleteAllAlertsCallsDelete1Times() throws Exception {159 when(repository.getReadableDatabase()).thenReturn(sqliteDatabase);160 when(repository.getWritableDatabase()).thenReturn(sqliteDatabase);161 alertRepository.updateMasterRepository(repository);162 alertRepository.deleteAllAlerts();163 Mockito.verify(sqliteDatabase, Mockito.times(1)).delete(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.isNull(String[].class));164 }165 @Test166 public void findByEntityIDReturnNotNUll() throws Exception {167 MatrixCursor matrixCursor = new MatrixCursor(alertColumns);168 matrixCursor.addRow(alertRow);169 when(repository.getReadableDatabase()).thenReturn(sqliteDatabase);170 when(repository.getWritableDatabase()).thenReturn(sqliteDatabase);171 alertRepository.updateMasterRepository(repository);172 Mockito.when(sqliteDatabase.rawQuery(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class))).thenReturn(matrixCursor);173 Assert.assertNotNull(alertRepository.findByEntityId("caseID"));174 }175 @Test176 public void findByEntityIdAndAlertNamesReturnNotNUll() throws Exception {177 MatrixCursor matrixCursor = new MatrixCursor(alertColumns);178 matrixCursor.addRow(alertRow);179 when(repository.getReadableDatabase()).thenReturn(sqliteDatabase);180 when(repository.getWritableDatabase()).thenReturn(sqliteDatabase);181 alertRepository.updateMasterRepository(repository);182 Mockito.when(sqliteDatabase.rawQuery(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class))).thenReturn(matrixCursor);183 Assert.assertNotNull(alertRepository.findByEntityIdAndAlertNames("caseID", "names1", "names2"));184 }185 @Test186 public void findOfflineByEntityIdAndAlertNamesReturnNotNUll() throws Exception {187 MatrixCursor matrixCursor = new MatrixCursor(alertColumns);188 matrixCursor.addRow(alertRow);189 when(repository.getReadableDatabase()).thenReturn(sqliteDatabase);190 when(repository.getWritableDatabase()).thenReturn(sqliteDatabase);191 alertRepository.updateMasterRepository(repository);192 Mockito.when(sqliteDatabase.rawQuery(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class))).thenReturn(matrixCursor);193 Assert.assertNotNull(alertRepository.findOfflineByEntityIdAndName("caseID", "names1", "names2"));194 }195 @Test196 public void findByEntityIdAndScheduleNameReturnNotNUll() throws Exception {197 MatrixCursor matrixCursor = new MatrixCursor(alertColumns);198 matrixCursor.addRow(alertRow);199 when(repository.getReadableDatabase()).thenReturn(sqliteDatabase);200 when(repository.getWritableDatabase()).thenReturn(sqliteDatabase);201 alertRepository.updateMasterRepository(repository);202 Mockito.when(sqliteDatabase.query(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(String[].class), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.isNull(String.class), org.mockito.ArgumentMatchers.isNull(String.class))).thenReturn(matrixCursor);203 Assert.assertNotNull(alertRepository.findByEntityIdAndScheduleName("caseID", "Schedulenames"));204 }205}...

Full Screen

Full Screen

Source:CreateRoomUnitTest.java Github

copy

Full Screen

2import java.io.IOException;3import org.junit.Before;4import org.junit.Test;5import org.junit.runner.RunWith;6import org.mockito.ArgumentMatchers;7import org.mockito.Mockito;8import org.springframework.beans.factory.annotation.Qualifier;9import org.springframework.boot.test.context.SpringBootTest;10import org.springframework.boot.test.mock.mockito.MockBean;11import org.springframework.boot.test.mock.mockito.SpyBean;12import org.springframework.test.context.junit4.SpringRunner;13import org.springframework.test.util.ReflectionTestUtils;14import site.neurotriumph.chat.www.interlocutor.Human;15import site.neurotriumph.chat.www.interlocutor.Interlocutor;16import site.neurotriumph.chat.www.interlocutor.Machine;17import site.neurotriumph.chat.www.pojo.Event;18import site.neurotriumph.chat.www.pojo.EventType;19import site.neurotriumph.chat.www.pojo.InterlocutorFoundEvent;20import site.neurotriumph.chat.www.room.Room;21import site.neurotriumph.chat.www.service.RoomService;22import site.neurotriumph.chat.www.storage.RoomStorage;23import site.neurotriumph.chat.www.util.MockedWebSocketSession;24import site.neurotriumph.chat.www.util.SpiedExecutorService;25import site.neurotriumph.chat.www.util.SpiedRandom;26@RunWith(SpringRunner.class)27@SpringBootTest28public class CreateRoomUnitTest {29 @SpyBean30 private RoomService roomService;31 @SpyBean32 private SpiedExecutorService executorService;33 @MockBean34 @Qualifier("spiedRandom")35 private SpiedRandom random;36 @MockBean37 private RoomStorage roomStorage;38 @Before39 public void before() {40 ReflectionTestUtils.setField(roomService, "random", random);41 ReflectionTestUtils.setField(roomService, "executorService", executorService);42 ReflectionTestUtils.setField(roomService, "roomStorage", roomStorage);43 }44 @Test45 public void shouldCreateRoomAndSendMessageAndThanTerminateMethodBecauseRandIsEquals0AndIsHumanMethodReturnsFalse()46 throws IOException {47 Mockito.doReturn(0)48 .when(random)49 .nextInt(ArgumentMatchers.eq(2));50 Mockito.doNothing()51 .when(executorService)52 .execute(ArgumentMatchers.any(Runnable.class));53 Interlocutor spiedSecondInterlocutor = Mockito.spy(new Machine(null));54 Interlocutor spiedFirstInterlocutor = Mockito.spy(new Human(new MockedWebSocketSession()));55 Room room = new Room(spiedFirstInterlocutor, spiedSecondInterlocutor);56 Room spiedRoom = Mockito.spy(room);57 Mockito.doReturn(spiedRoom)58 .when(roomStorage)59 .createNew(60 ArgumentMatchers.eq(spiedFirstInterlocutor),61 ArgumentMatchers.eq(spiedSecondInterlocutor));62 Event eventForSecondInterlocutor = new Event(EventType.INIT_CHAT_MESSAGE);63 Mockito.doNothing()64 .when(spiedSecondInterlocutor)65 .send(ArgumentMatchers.eq(eventForSecondInterlocutor));66 Mockito.doNothing()67 .when(spiedFirstInterlocutor)68 .send(ArgumentMatchers.any(InterlocutorFoundEvent.class));69 Mockito.doNothing()70 .when(roomService)71 .sendMachineResponse(72 ArgumentMatchers.eq(null),73 ArgumentMatchers.eq(spiedFirstInterlocutor),74 ArgumentMatchers.eq(spiedRoom));75 roomService.create(spiedFirstInterlocutor, spiedSecondInterlocutor);76 Mockito.verify(roomStorage, Mockito.times(1))77 .createNew(78 ArgumentMatchers.eq(spiedFirstInterlocutor),79 ArgumentMatchers.eq(spiedSecondInterlocutor));80 Mockito.verify(random, Mockito.times(1))81 .nextInt(ArgumentMatchers.eq(2));82 Mockito.verify(spiedRoom, Mockito.times(0))83 .swapInterlocutors();84 Mockito.verify(spiedFirstInterlocutor, Mockito.times(1))85 .send(ArgumentMatchers.any(InterlocutorFoundEvent.class));86 Mockito.verify(executorService, Mockito.times(0))87 .execute(ArgumentMatchers.any(Runnable.class));88 }89 @Test90 public void shouldCreateRoomAndSendMessagesButRandIsEquals1AndIsHumanMethodReturnsFalse()91 throws IOException, InterruptedException {92 Mockito.doReturn(1)93 .when(random)94 .nextInt(ArgumentMatchers.eq(2));95 Machine spiedSecondInterlocutor = Mockito.spy(new Machine(null));96 Interlocutor spiedFirstInterlocutor = Mockito.spy(new Human(new MockedWebSocketSession()));97 Room room = new Room(spiedFirstInterlocutor, spiedSecondInterlocutor);98 Room spiedRoom = Mockito.spy(room);99 Mockito.doReturn(spiedRoom)100 .when(roomStorage)101 .createNew(102 ArgumentMatchers.eq(spiedFirstInterlocutor),103 ArgumentMatchers.eq(spiedSecondInterlocutor));104 Mockito.doNothing()105 .when(spiedSecondInterlocutor)106 .send(ArgumentMatchers.eq(new Event(EventType.INIT_CHAT_MESSAGE)));107 InterlocutorFoundEvent interlocutorFoundEventForFirstInterlocutor = new InterlocutorFoundEvent(false);108 Mockito.doNothing()109 .when(spiedFirstInterlocutor)110 .send(ArgumentMatchers.eq(interlocutorFoundEventForFirstInterlocutor));111 Mockito.doNothing()112 .when(roomService)113 .sendMachineResponse(114 ArgumentMatchers.eq(null),115 ArgumentMatchers.eq(spiedFirstInterlocutor),116 ArgumentMatchers.eq(spiedRoom));117 roomService.create(spiedFirstInterlocutor, spiedSecondInterlocutor);118 Thread.sleep(1000);119 Mockito.verify(roomStorage, Mockito.times(1))120 .createNew(121 ArgumentMatchers.eq(spiedFirstInterlocutor),122 ArgumentMatchers.eq(spiedSecondInterlocutor));123 Mockito.verify(random, Mockito.times(1))124 .nextInt(ArgumentMatchers.eq(2));125 Mockito.verify(spiedRoom, Mockito.times(1))126 .swapInterlocutors();127 Mockito.verify(spiedFirstInterlocutor, Mockito.times(1))128 .send(ArgumentMatchers.eq(interlocutorFoundEventForFirstInterlocutor));129 Mockito.verify(executorService, Mockito.times(1))130 .execute(ArgumentMatchers.any(Runnable.class));131 }132 @Test133 public void shouldCreateRoomAndSendMessagesAndThanTerminateMethodBecauseRandIsEquals1AndIsHumanMethodReturnsTrue()134 throws IOException {135 Mockito.doReturn(1)136 .when(random)137 .nextInt(ArgumentMatchers.eq(2));138 Interlocutor spiedSecondInterlocutor = Mockito.spy(new Human(new MockedWebSocketSession()));139 Interlocutor spiedFirstInterlocutor = Mockito.spy(new Human(new MockedWebSocketSession()));140 Room room = new Room(spiedFirstInterlocutor, spiedSecondInterlocutor);141 Room spiedRoom = Mockito.spy(room);142 Mockito.doReturn(spiedRoom)143 .when(roomStorage)144 .createNew(145 ArgumentMatchers.eq(spiedFirstInterlocutor),146 ArgumentMatchers.eq(spiedSecondInterlocutor));147 Mockito.doNothing()148 .when(spiedSecondInterlocutor)149 .send(ArgumentMatchers.any(InterlocutorFoundEvent.class));150 Mockito.doNothing()151 .when(spiedFirstInterlocutor)152 .send(ArgumentMatchers.any(InterlocutorFoundEvent.class));153 roomService.create(spiedFirstInterlocutor, spiedSecondInterlocutor);154 Mockito.verify(roomStorage, Mockito.times(1))155 .createNew(156 ArgumentMatchers.eq(spiedFirstInterlocutor),157 ArgumentMatchers.eq(spiedSecondInterlocutor));158 Mockito.verify(random, Mockito.times(1))159 .nextInt(ArgumentMatchers.eq(2));160 Mockito.verify(spiedRoom, Mockito.times(1))161 .swapInterlocutors();162 Mockito.verify(spiedFirstInterlocutor, Mockito.times(1))163 .send(ArgumentMatchers.any(InterlocutorFoundEvent.class));164 Mockito.verify(spiedSecondInterlocutor, Mockito.times(1))165 .send(ArgumentMatchers.any(InterlocutorFoundEvent.class));166 }167 @Test168 public void shouldCreateRoomAndSendMessagesAndThanTerminateMethodBecauseRandIsEquals0AndIsHumanMethodReturnsTrue()169 throws IOException {170 Mockito.doReturn(0)171 .when(random)172 .nextInt(ArgumentMatchers.eq(2));173 Interlocutor spiedSecondInterlocutor = Mockito.spy(new Human(new MockedWebSocketSession()));174 Interlocutor spiedFirstInterlocutor = Mockito.spy(new Human(new MockedWebSocketSession()));175 Room room = new Room(spiedFirstInterlocutor, spiedSecondInterlocutor);176 Room spiedRoom = Mockito.spy(room);177 Mockito.doReturn(spiedRoom)178 .when(roomStorage)179 .createNew(180 ArgumentMatchers.eq(spiedFirstInterlocutor),181 ArgumentMatchers.eq(spiedSecondInterlocutor));182 InterlocutorFoundEvent interlocutorFoundEventForSecondInterlocutor = new InterlocutorFoundEvent(false);183 Mockito.doNothing()184 .when(spiedSecondInterlocutor)185 .send(ArgumentMatchers.eq(interlocutorFoundEventForSecondInterlocutor));186 InterlocutorFoundEvent interlocutorFoundEventForFirstInterlocutor = new InterlocutorFoundEvent(true);187 Mockito.doNothing()188 .when(spiedFirstInterlocutor)189 .send(ArgumentMatchers.eq(interlocutorFoundEventForFirstInterlocutor));190 roomService.create(spiedFirstInterlocutor, spiedSecondInterlocutor);191 Mockito.verify(roomStorage, Mockito.times(1))192 .createNew(193 ArgumentMatchers.eq(spiedFirstInterlocutor),194 ArgumentMatchers.eq(spiedSecondInterlocutor));195 Mockito.verify(random, Mockito.times(1))196 .nextInt(ArgumentMatchers.eq(2));197 Mockito.verify(spiedRoom, Mockito.times(0))198 .swapInterlocutors();199 Mockito.verify(spiedFirstInterlocutor, Mockito.times(1))200 .send(ArgumentMatchers.eq(interlocutorFoundEventForFirstInterlocutor));201 Mockito.verify(spiedSecondInterlocutor, Mockito.times(1))202 .send(ArgumentMatchers.eq(interlocutorFoundEventForSecondInterlocutor));203 }204}...

Full Screen

Full Screen

Source:FindInterlocutorUnitTest.java Github

copy

Full Screen

...8import static org.junit.Assert.assertTrue;9import org.junit.Before;10import org.junit.Test;11import org.junit.runner.RunWith;12import org.mockito.ArgumentMatchers;13import org.mockito.Mockito;14import org.springframework.beans.factory.annotation.Qualifier;15import org.springframework.beans.factory.annotation.Value;16import org.springframework.boot.test.context.SpringBootTest;17import org.springframework.boot.test.mock.mockito.MockBean;18import org.springframework.boot.test.mock.mockito.SpyBean;19import org.springframework.test.context.junit4.SpringRunner;20import org.springframework.test.util.ReflectionTestUtils;21import site.neurotriumph.chat.www.interlocutor.Human;22import site.neurotriumph.chat.www.interlocutor.Interlocutor;23import site.neurotriumph.chat.www.interlocutor.Machine;24import site.neurotriumph.chat.www.pojo.Event;25import site.neurotriumph.chat.www.pojo.EventType;26import site.neurotriumph.chat.www.service.LobbyService;27import site.neurotriumph.chat.www.service.RoomService;28import site.neurotriumph.chat.www.storage.LobbyStorage;29import site.neurotriumph.chat.www.util.MockedWebSocketSession;30import site.neurotriumph.chat.www.util.SpiedRandom;31@RunWith(SpringRunner.class)32@SpringBootTest33public class FindInterlocutorUnitTest {34 @Value("${app.lobby_spent_time}")35 private long lobbySpentTime;36 @SpyBean37 private LobbyService lobbyService;38 @MockBean39 private RoomService roomService;40 @MockBean41 private LobbyStorage lobbyStorage;42 @MockBean43 @Qualifier("spiedRandom")44 private SpiedRandom random;45 @MockBean46 private ScheduledExecutorService scheduledExecutorService;47 @Before48 public void before() {49 ReflectionTestUtils.setField(lobbyService, "random", random);50 ReflectionTestUtils.setField(lobbyService, "lobbyStorage", lobbyStorage);51 ReflectionTestUtils.setField(lobbyService, "scheduledExecutorService", scheduledExecutorService);52 }53 @Test54 public void afterSpentTimeInLobby_shouldCreateRoom() throws IOException {55 Human spiedHuman = Mockito.mock(Human.class);56 Mockito.doReturn(true)57 .when(lobbyService)58 .excludeFromLobby(ArgumentMatchers.eq(spiedHuman));59 Mockito.doReturn(new Machine(null))60 .when(lobbyService)61 .findMachine();62 lobbyService.afterSpentTimeInLobby(spiedHuman);63 Mockito.verify(lobbyService, Mockito.times(1))64 .excludeFromLobby(ArgumentMatchers.eq(spiedHuman));65 Mockito.verify(lobbyService, Mockito.times(1))66 .findMachine();67 Mockito.verify(spiedHuman, Mockito.times(0))68 .send(ArgumentMatchers.eq(new Event(EventType.NO_ONE_TO_TALK)));69 Mockito.verify(roomService, Mockito.times(1))70 .create(71 ArgumentMatchers.eq(spiedHuman),72 ArgumentMatchers.any(Machine.class));73 }74 @Test75 public void afterSpentTimeInLobby_shouldTerminateMethodBecauseNeuralNetworkIsEmpty() throws IOException {76 Human spiedHuman = Mockito.mock(Human.class);77 Mockito.doNothing()78 .when(spiedHuman)79 .send(ArgumentMatchers.eq(new Event(EventType.NO_ONE_TO_TALK)));80 Mockito.doReturn(true)81 .when(lobbyService)82 .excludeFromLobby(ArgumentMatchers.eq(spiedHuman));83 Mockito.doReturn(null)84 .when(lobbyService)85 .findMachine();86 lobbyService.afterSpentTimeInLobby(spiedHuman);87 Mockito.verify(lobbyService, Mockito.times(1))88 .excludeFromLobby(ArgumentMatchers.eq(spiedHuman));89 Mockito.verify(lobbyService, Mockito.times(1))90 .findMachine();91 Mockito.verify(spiedHuman, Mockito.times(1))92 .send(ArgumentMatchers.eq(new Event(EventType.NO_ONE_TO_TALK)));93 Mockito.verify(roomService, Mockito.times(0))94 .create(95 ArgumentMatchers.eq(spiedHuman),96 ArgumentMatchers.any(Machine.class));97 }98 @Test99 public void afterSpentTimeInLobby_shouldTerminateMethodBecauseLobbyNotContainsUser() throws IOException {100 Human human = new Human(new MockedWebSocketSession());101 Mockito.doReturn(false)102 .when(lobbyService)103 .excludeFromLobby(ArgumentMatchers.eq(human));104 lobbyService.afterSpentTimeInLobby(human);105 Mockito.verify(lobbyService, Mockito.times(0))106 .findMachine();107 }108 @Test109 public void shouldAddHumanToLobbyThenScheduleRunnableAndReturnNullBecauseLobbySizeIsZero() {110 Human human = new Human(new MockedWebSocketSession());111 Mockito.doReturn(1)112 .when(random)113 .nextInt(ArgumentMatchers.eq(2));114 Mockito.doReturn(0)115 .when(lobbyStorage)116 .size();117 Mockito.doNothing()118 .when(lobbyStorage)119 .add(120 ArgumentMatchers.eq(human),121 ArgumentMatchers.eq(null));122 Mockito.doReturn(null)123 .when(scheduledExecutorService)124 .schedule(125 ArgumentMatchers.any(Runnable.class),126 ArgumentMatchers.eq(lobbySpentTime),127 ArgumentMatchers.eq(TimeUnit.MILLISECONDS));128 Interlocutor interlocutor = lobbyService.findInterlocutor(human);129 assertNull(interlocutor);130 Mockito.verify(random, Mockito.times(1))131 .nextInt(ArgumentMatchers.eq(2));132 Mockito.verify(lobbyStorage, Mockito.times(1))133 .size();134 Mockito.verify(lobbyStorage, Mockito.times(1))135 .add(136 ArgumentMatchers.eq(human),137 ArgumentMatchers.eq(null));138 Mockito.verify(scheduledExecutorService, Mockito.times(1))139 .schedule(140 ArgumentMatchers.any(Runnable.class),141 ArgumentMatchers.eq(lobbySpentTime),142 ArgumentMatchers.eq(TimeUnit.MILLISECONDS));143 }144 @Test145 public void shouldReturnHumanBecauseLobbySizeIsNotZero() {146 Human foundHuman = new Human(new MockedWebSocketSession());147 Mockito.doReturn(1)148 .when(random)149 .nextInt(ArgumentMatchers.eq(2));150 Mockito.doReturn(1)151 .when(lobbyStorage)152 .size();153 Mockito.doReturn(foundHuman)154 .when(lobbyStorage)155 .getFirst();156 Mockito.doReturn(true)157 .when(lobbyService)158 .excludeFromLobby(ArgumentMatchers.eq(foundHuman));159 Mockito.doReturn(null)160 .when(lobbyService)161 .findMachine();162 Interlocutor interlocutor = lobbyService.findInterlocutor(new Human(new MockedWebSocketSession()));163 assertNotNull(interlocutor);164 assertTrue(interlocutor.isHuman());165 Mockito.verify(random, Mockito.times(1))166 .nextInt(ArgumentMatchers.eq(2));167 Mockito.verify(lobbyStorage, Mockito.times(1))168 .size();169 Mockito.verify(lobbyStorage, Mockito.times(1))170 .getFirst();171 Mockito.verify(lobbyService, Mockito.times(1))172 .excludeFromLobby(ArgumentMatchers.eq(foundHuman));173 }174 @Test175 public void shouldNotFindNeuralNetworkAndReturnHumanBecauseLobbySizeIsNotZero() {176 Human foundHuman = new Human(new MockedWebSocketSession());177 Mockito.doReturn(0)178 .when(random)179 .nextInt(ArgumentMatchers.eq(2));180 Mockito.doReturn(null)181 .when(lobbyService)182 .findMachine();183 Mockito.doReturn(1)184 .when(lobbyStorage)185 .size();186 Mockito.doReturn(foundHuman)187 .when(lobbyStorage)188 .getFirst();189 Mockito.doReturn(true)190 .when(lobbyService)191 .excludeFromLobby(ArgumentMatchers.eq(foundHuman));192 Interlocutor interlocutor = lobbyService.findInterlocutor(new Human(new MockedWebSocketSession()));193 assertNotNull(interlocutor);194 assertTrue(interlocutor.isHuman());195 Mockito.verify(random, Mockito.times(1))196 .nextInt(ArgumentMatchers.eq(2));197 Mockito.verify(lobbyService, Mockito.times(1))198 .findMachine();199 Mockito.verify(lobbyStorage, Mockito.times(1))200 .size();201 Mockito.verify(lobbyStorage, Mockito.times(1))202 .getFirst();203 Mockito.verify(lobbyService, Mockito.times(1))204 .excludeFromLobby(ArgumentMatchers.eq(foundHuman));205 }206 @Test207 public void shouldFindNeuralNetworkAndReturnIt() {208 Mockito.doReturn(0)209 .when(random)210 .nextInt(ArgumentMatchers.eq(2));211 Mockito.doReturn(new Machine(null))212 .when(lobbyService)213 .findMachine();214 Interlocutor interlocutor = lobbyService.findInterlocutor(new Human(new MockedWebSocketSession()));215 assertNotNull(interlocutor);216 assertFalse(interlocutor.isHuman());217 Mockito.verify(random, Mockito.times(1))218 .nextInt(ArgumentMatchers.eq(2));219 Mockito.verify(lobbyService, Mockito.times(1))220 .findMachine();221 }222}...

Full Screen

Full Screen

Source:RandomCodeGeneratorTest.java Github

copy

Full Screen

...12import org.junit.Test;13import org.junit.rules.ExpectedException;14import org.junit.runner.RunWith;15import org.mitre.synthea.world.concepts.HealthRecord.Code;16import org.mockito.ArgumentMatchers;17import org.mockito.Mock;18import org.mockito.Mockito;19import org.mockito.junit.MockitoJUnitRunner;20import org.springframework.http.HttpEntity;21import org.springframework.http.HttpMethod;22import org.springframework.http.HttpStatus;23import org.springframework.http.ResponseEntity;24import org.springframework.web.client.RestClientException;25import org.springframework.web.client.RestTemplate;26@RunWith(MockitoJUnitRunner.class)27public class RandomCodeGeneratorTest {28 private static final int SEED = 1234;29 private static final String VALUE_SET_URI = SNOMED_URI + "?fhir_vs=ecl/<<131148009";30 private static final String PATH = "wiremock/RandomCodeGeneratorTest/__files/";31 private final Code code = new Code("SNOMED-CT", "38341003", "Hypertension");32 @Rule33 public ExpectedException thrown = ExpectedException.none();34 @Mock35 private RestTemplate restTemplate;36 @Before37 public void setup() {38 RandomCodeGenerator.restTemplate = restTemplate;39 }40 @Test41 public void getCode() {42 Mockito43 .when(restTemplate.exchange(ArgumentMatchers.anyString(),44 ArgumentMatchers.eq(HttpMethod.GET),45 ArgumentMatchers.<HttpEntity<?>>any(),46 ArgumentMatchers.<Class<String>>any()))47 .thenReturn(new ResponseEntity<String>(getResponseToStub("codes.json"), HttpStatus.OK));48 Code code = RandomCodeGenerator.getCode(VALUE_SET_URI, SEED, this.code);49 Assert.assertEquals(SNOMED_URI, code.system);50 Assert.assertEquals("312858004", code.code);51 Assert.assertEquals("Neonatal tracheobronchial haemorrhage", code.display);52 }53 @Test54 public void throwsWhenNoExpansion() {55 thrown.expect(RuntimeException.class);56 thrown.expectMessage("ValueSet does not contain expansion");57 Mockito58 .when(restTemplate.exchange(ArgumentMatchers.anyString(),59 ArgumentMatchers.eq(HttpMethod.GET),60 ArgumentMatchers.<HttpEntity<?>>any(),61 ArgumentMatchers.<Class<String>>any()))62 .thenReturn(new ResponseEntity<String>(getResponseToStub("noExpansion.ValueSet.json"),63 HttpStatus.OK));64 RandomCodeGenerator.getCode(VALUE_SET_URI, SEED, this.code);65 }66 @Test67 public void throwsWhenNoTotal() {68 thrown.expect(RuntimeException.class);69 thrown.expectMessage("No total element in ValueSet expand result");70 Mockito71 .when(restTemplate.exchange(ArgumentMatchers.anyString(),72 ArgumentMatchers.eq(HttpMethod.GET),73 ArgumentMatchers.<HttpEntity<?>>any(),74 ArgumentMatchers.<Class<String>>any()))75 .thenReturn(new ResponseEntity<String>(getResponseToStub("noTotal.ValueSet.json"),76 HttpStatus.OK));77 RandomCodeGenerator.getCode(VALUE_SET_URI, SEED, this.code);78 }79 @Test80 public void throwsWhenNoContains() {81 thrown.expect(RuntimeException.class);82 thrown.expectMessage("ValueSet expansion does not contain any codes");83 Mockito84 .when(restTemplate.exchange(ArgumentMatchers.anyString(),85 ArgumentMatchers.eq(HttpMethod.GET),86 ArgumentMatchers.<HttpEntity<?>>any(),87 ArgumentMatchers.<Class<String>>any()))88 .thenReturn(new ResponseEntity<String>(getResponseToStub("noContains.ValueSet.json"),89 HttpStatus.OK));90 RandomCodeGenerator.getCode(VALUE_SET_URI, SEED, this.code);91 }92 @Test93 public void throwsWhenMissingCodeElements() {94 thrown.expect(RuntimeException.class);95 thrown.expectMessage("ValueSet contains element does not contain system, code and display");96 Mockito97 .when(restTemplate.exchange(ArgumentMatchers.anyString(),98 ArgumentMatchers.eq(HttpMethod.GET),99 ArgumentMatchers.<HttpEntity<?>>any(),100 ArgumentMatchers.<Class<String>>any()))101 .thenReturn(new ResponseEntity<String>(102 getResponseToStub("missingCodeElements.ValueSet.json"), HttpStatus.OK));103 RandomCodeGenerator.getCode(VALUE_SET_URI, SEED, this.code);104 }105 @Test106 public void throwsWhenInvalidResponse() {107 thrown.expect(RuntimeException.class);108 thrown.expectMessage("JsonProcessingException while parsing valueSet response");109 Mockito110 .when(restTemplate.exchange(ArgumentMatchers.anyString(),111 ArgumentMatchers.eq(HttpMethod.GET),112 ArgumentMatchers.<HttpEntity<?>>any(),113 ArgumentMatchers.<Class<String>>any()))114 .thenReturn(new ResponseEntity<String>(115 StringUtils.chop(getResponseToStub("noExpansion.ValueSet.json")),116 HttpStatus.OK));117 RandomCodeGenerator.getCode(VALUE_SET_URI, SEED, this.code);118 }119 @Test120 public void throwsWhenRestClientFailed() {121 thrown.expect(RestClientException.class);122 thrown.expectMessage("RestClientException while fetching valueSet response");123 Mockito124 .when(restTemplate.exchange(ArgumentMatchers.anyString(),125 ArgumentMatchers.eq(HttpMethod.GET),126 ArgumentMatchers.<HttpEntity<?>>any(),127 ArgumentMatchers.<Class<String>>any()))128 .thenThrow(new RestClientException(129 "RestClientException while fetching valueSet response"));130 RandomCodeGenerator.getCode(VALUE_SET_URI, SEED, this.code);131 }132 @Test133 public void filterCodesTest() {134 Mockito135 .when(restTemplate.exchange(ArgumentMatchers.anyString(),136 ArgumentMatchers.eq(HttpMethod.GET),137 ArgumentMatchers.<HttpEntity<?>>any(),138 ArgumentMatchers.<Class<String>>any()))139 .thenReturn(new ResponseEntity<String>(getResponseToStub("codes.json"), HttpStatus.OK));140 Code code = RandomCodeGenerator.getCode(VALUE_SET_URI + "&filter=tracheobronchial",141 SEED, this.code);142 Assert.assertTrue("Verify filter", code.display.contains("tracheobronchial"));143 }144 @Test145 public void invalidValueSetUrlTest() {146 Code code = RandomCodeGenerator.getCode("", SEED, this.code);147 Assert.assertEquals("SNOMED-CT", code.system);148 Assert.assertEquals("38341003", code.code);149 Assert.assertEquals("Hypertension", code.display);150 }151 @After152 public void cleanup() {...

Full Screen

Full Screen

Source:FlashForgeDreamerClientTest.java Github

copy

Full Screen

...3import com.crow.iot.esp32.crowOS.backend.printer.Printer;4import org.junit.jupiter.api.BeforeEach;5import org.junit.jupiter.api.Test;6import org.junit.jupiter.api.extension.ExtendWith;7import org.mockito.ArgumentMatchers;8import org.mockito.Mockito;9import org.mockito.Spy;10import org.mockito.junit.jupiter.MockitoExtension;11import org.springframework.boot.test.context.SpringBootTest;12import static org.assertj.core.api.Assertions.assertThat;13import static org.junit.jupiter.api.Assertions.assertThrows;14/**15 * @author : error2316 * Created : 12/06/202117 */18@SpringBootTest19@ExtendWith (MockitoExtension.class)20class FlashForgeDreamerClientTest {21 @Spy22 FlashForgeDreamerClient client;23 Printer printer;24 @BeforeEach25 void setUp() {26 this.printer = new Printer();27 this.printer.setId(1L);28 this.printer.setMachineIp("192.168.0.3");29 this.printer.setMachinePort(8899);30 }31 @Test32 void whenUpdateGeneralInfo_thanSuccess() {33 String answer = "CMD M115 Received.\n" +34 "Machine Type: Flashforge Dreamer\n" +35 "Machine Name: error23_dreamer\n" +36 "Firmware: V2.15 20200917\n" +37 "SN: 55003b-324d5015-20393156\n" +38 "X: 230 Y: 150 Z: 140\n" +39 "Tool Count: 2\n" +40 "ok";41 Mockito.doReturn(answer)42 .when(this.client)43 .sendCommand(ArgumentMatchers.matches("192.168.0.3"),44 ArgumentMatchers.eq(8899),45 ArgumentMatchers.eq(FlashForgeDreamerCommands.GET_GENERAL_INFO),46 ArgumentMatchers.eq(null));47 this.client.updateGeneralInfo(this.printer);48 assertThat("Flashforge Dreamer").isEqualTo(this.printer.getMachineType());49 assertThat("error23_dreamer").isEqualTo(this.printer.getMachineName());50 assertThat("V2.15 20200917").isEqualTo(this.printer.getFirmware());51 assertThat(230.0).isEqualTo(this.printer.getMaxX());52 assertThat(150.0).isEqualTo(this.printer.getMaxY());53 assertThat(140.0).isEqualTo(this.printer.getMaxZ());54 assertThat(2).isEqualTo(this.printer.getExtruderNumber());55 }56 @Test57 void whenUpdateTemperature_thanSuccess() {58 String answer = "CMD M105 Received.\n" +59 "T0:35 /0 T1:20 /0 B:25 /0\n" +60 "ok";61 Mockito.doReturn(answer)62 .when(this.client)63 .sendCommand(ArgumentMatchers.matches("192.168.0.3"),64 ArgumentMatchers.eq(8899),65 ArgumentMatchers.eq(FlashForgeDreamerCommands.GET_TEMPERATURE),66 ArgumentMatchers.eq(null));67 this.client.updateTemperature(this.printer);68 assertThat(35).isEqualTo(this.printer.getTemperatureExtruderLeft());69 assertThat(20).isEqualTo(this.printer.getTemperatureExtruderRight());70 assertThat(25).isEqualTo(this.printer.getTemperatureBed());71 }72 @Test73 void whenUpdatePositions_thanSuccess() {74 String answer = "CMD M114 Received.\n" +75 "X:123.001 Y:79.9912 Z:10.5 A:0 B:0\n" +76 "ok";77 Mockito.doReturn(answer)78 .when(this.client)79 .sendCommand(ArgumentMatchers.matches("192.168.0.3"),80 ArgumentMatchers.eq(8899),81 ArgumentMatchers.eq(FlashForgeDreamerCommands.GET_POSITIONS),82 ArgumentMatchers.eq(null));83 this.client.updatePositions(this.printer);84 assertThat(this.printer.getX()).isEqualTo(123.001);85 assertThat(this.printer.getY()).isEqualTo(79.9912);86 assertThat(this.printer.getZ()).isEqualTo(10.5);87 }88 @Test89 void whenUpdatePrintingProgress_thanSuccess() {90 String answer = "CMD M27 Received.\n" +91 "SD printing byte 896065/5019767\n" +92 "ok";93 Mockito.doReturn(answer)94 .when(this.client)95 .sendCommand(ArgumentMatchers.matches("192.168.0.3"),96 ArgumentMatchers.eq(8899),97 ArgumentMatchers.eq(FlashForgeDreamerCommands.GET_PRINTING_PROGRESS),98 ArgumentMatchers.eq(null));99 this.client.updatePrintingProgress(this.printer);100 assertThat(this.printer.getPrintingProgress()).isEqualTo(17.85);101 }102 @Test103 void whenSetColor_thanSuccess() {104 Mockito.doReturn("")105 .when(this.client)106 .sendCommand(ArgumentMatchers.matches("192.168.0.3"),107 ArgumentMatchers.eq(8899),108 ArgumentMatchers.eq(FlashForgeDreamerCommands.SET_COLOR),109 ArgumentMatchers.eq("r255 g0 b0 F0"));110 this.client.setColor(this.printer, ColorRGB.RED);111 Mockito.verify(this.client, Mockito.times(1)).sendCommand(ArgumentMatchers.matches("192.168.0.3"),112 ArgumentMatchers.eq(8899),113 ArgumentMatchers.eq(FlashForgeDreamerCommands.SET_COLOR),114 ArgumentMatchers.eq("r255 g0 b0 F0"));115 }116 @Test117 void whenSendHello_thanSuccess() {118 Mockito.doReturn("")119 .when(this.client)120 .sendCommand(ArgumentMatchers.matches("192.168.0.3"),121 ArgumentMatchers.eq(8899),122 ArgumentMatchers.eq(FlashForgeDreamerCommands.HELLO),123 ArgumentMatchers.eq(null));124 this.client.sendHello(this.printer);125 Mockito.verify(this.client, Mockito.times(1)).sendCommand(ArgumentMatchers.matches("192.168.0.3"),126 ArgumentMatchers.eq(8899),127 ArgumentMatchers.eq(FlashForgeDreamerCommands.HELLO),128 ArgumentMatchers.eq(null));129 }130 @Test131 void whenSendHello_thanFail() {132 assertThrows(FlashForgeDreamerClientException.class, () -> this.client.sendHello(this.printer));133 }134 @Test135 void whenSendBuy_thanSuccess() {136 Mockito.doReturn("")137 .when(this.client)138 .sendCommand(ArgumentMatchers.matches("192.168.0.3"),139 ArgumentMatchers.eq(8899),140 ArgumentMatchers.eq(FlashForgeDreamerCommands.BUY),141 ArgumentMatchers.eq(null));142 this.client.sendBuy(this.printer);143 Mockito.verify(this.client, Mockito.times(1)).sendCommand(ArgumentMatchers.matches("192.168.0.3"),144 ArgumentMatchers.eq(8899),145 ArgumentMatchers.eq(FlashForgeDreamerCommands.BUY),146 ArgumentMatchers.eq(null));147 }148}...

Full Screen

Full Screen

Source:ArgumentMatcherTest.java Github

copy

Full Screen

1package pl.javastart.junittestingcourse.examples.mockito.behaviour.argumentmatcher;2import org.junit.jupiter.api.Test;3import org.mockito.ArgumentMatcher;4import org.mockito.ArgumentMatchers;5import org.mockito.Mockito;6import java.io.File;7import java.util.List;8import static org.assertj.core.api.Assertions.assertThat;9import static org.mockito.ArgumentMatchers.intThat;10import static org.mockito.Mockito.mock;11import static org.mockito.Mockito.when;12public class ArgumentMatcherTest {13 @Test14 public void shouldHandleVoidMethod() {15 User user = mock(User.class);16 Mockito.doThrow(new IllegalStateException()).when(user).setName(ArgumentMatchers.any());17 user.setName("Basia");18 user.setName("Kasia");19 }20 @Test21 public void simpleTypeMatchers() {22 ArgumentMatchers.anyString();23 ArgumentMatchers.anyByte();24 ArgumentMatchers.anyShort();25 ArgumentMatchers.anyInt();26 ArgumentMatchers.anyLong();27 ArgumentMatchers.anyFloat();28 ArgumentMatchers.anyDouble();29 ArgumentMatchers.anyChar();30 ArgumentMatchers.anyString();31 }32 @Test33 public void collectionsMatchers() {34 ArgumentMatchers.anySet();35 ArgumentMatchers.anyList();36 ArgumentMatchers.anyMap();37 ArgumentMatchers.anyCollection();38 ArgumentMatchers.anyIterable();39 }40 @Test41 public void eqMatchers() {42 String text = "";43 ArgumentMatchers.eq("");44 ArgumentMatchers.refEq(text);45 }46 @Test47 public void stringMatchers() {48 ArgumentMatchers.contains("string part");49 ArgumentMatchers.startsWith("string start");50 ArgumentMatchers.endsWith("string end");51 ArgumentMatchers.matches("regex");52 }53 @Test54 public void conditionMatchers() {55 ArgumentMatchers.intThat(value -> value > 2);56 ArgumentMatchers.longThat(value -> value < 100);57 ArgumentMatchers.booleanThat(value -> !value);58 }59 @Test60 public void shouldCheckIfAdult() {61 AdultChecker adultChecker = mock(AdultChecker.class);62 when(adultChecker.checkIfAdult(intThat(age -> age < 18))).thenReturn(false);63 when(adultChecker.checkIfAdult(intThat(age -> age >= 18))).thenReturn(true);64 assertThat(adultChecker.checkIfAdult(5)).isFalse();65 assertThat(adultChecker.checkIfAdult(30)).isTrue();66 }67 @Test68 public void customMatcher() {69 File file = new File("file.txt");70 File fileMatcher = ArgumentMatchers.argThat((ArgumentMatcher<File>) argument -> file.getName().endsWith(".txt"));71 ArgumentMatchers.argThat(new ArgumentMatcher<File>() {72 @Override73 public boolean matches(File argument) {74 return argument.getName().endsWith(".txt");75 }76 });77 }78 @Test79 public void nullMatchers() {80 ArgumentMatchers.notNull(); // to samo co ArgumentMatchers.isNotNull()81 ArgumentMatchers.isNotNull(); // to samo co ArgumentMatchers.notNull()82 ArgumentMatchers.isNull();83 ArgumentMatchers.nullable(Clazz.class); // null or type84 }85 @Test86 public void anyMatchers() {87 ArgumentMatchers.any();88 ArgumentMatchers.any(String.class);89 }90 static class Clazz {91 }92}...

Full Screen

Full Screen

Source:UserServiceTest.java Github

copy

Full Screen

...5import org.hamcrest.CoreMatchers;6import org.junit.Assert;7import org.junit.jupiter.api.Test;8import org.junit.runner.RunWith;9import org.mockito.ArgumentMatchers;10import org.mockito.Mockito;11import org.springframework.beans.factory.annotation.Autowired;12import org.springframework.boot.test.context.SpringBootTest;13import org.springframework.boot.test.mock.mockito.MockBean;14import org.springframework.security.crypto.password.PasswordEncoder;15import org.springframework.test.context.junit4.SpringRunner;16import java.util.Collections;17import static org.junit.jupiter.api.Assertions.*;18@RunWith(SpringRunner.class)19@SpringBootTest20class UserServiceTest {21 @Autowired22 private UserService userService;23 @MockBean24 private UserRepository userRepository;25 @MockBean26 private MailSender mailSender;27 @MockBean28 private PasswordEncoder passwordEncoder;29 @Test30 public void addUser() {31 User user = new User();32 user.setEmail("some@mail.ru");33 boolean isUserCreated = userService.addUser(user);34 Assert.assertTrue(isUserCreated);35 Assert.assertNotNull(user.getActivationCode());36 Assert.assertTrue(CoreMatchers.is(user.getRoles()).matches(Collections.singleton(Role.USER)));37 Mockito.verify(userRepository, Mockito.times(1)).save(user);38 Mockito.verify(mailSender, Mockito.times(1))39 .send(40 ArgumentMatchers.eq(user.getEmail()),41 ArgumentMatchers.anyString(),42 ArgumentMatchers.anyString()43 );44 }45 @Test46 public void addUserFailTest() {47 User user = new User();48 user.setUsername("John");49 Mockito.doReturn(new User())50 .when(userRepository)51 .findByUsername("John");52 boolean isUserCreated = userService.addUser(user);53 Assert.assertFalse(isUserCreated);54 Mockito.verify(userRepository, Mockito.times(0)).save(ArgumentMatchers.any(User.class));55 Mockito.verify(mailSender, Mockito.times(0))56 .send(57 ArgumentMatchers.anyString(),58 ArgumentMatchers.anyString(),59 ArgumentMatchers.anyString()60 );61 }62 @Test63 public void activateUser() {64 User user = new User();65 user.setActivationCode("bingo");66 Mockito.doReturn(user)67 .when(userRepository)68 .findByActivationCode("activate");69 boolean isUserActivated = userService.activateUser("activate");70 Assert.assertTrue(isUserActivated);71 Assert.assertNull(user.getActivationCode());72 Mockito.verify(userRepository, Mockito.times(1)).save(user);73 }74 @Test75 public void activateUserFailTest() {76 boolean isUserActivated = userService.activateUser("activate me");77 Assert.assertFalse(isUserActivated);78 Mockito.verify(userRepository, Mockito.times(0)).save(ArgumentMatchers.any(User.class));79 }80}...

Full Screen

Full Screen

Source:UserSeviceTest.java Github

copy

Full Screen

...5import org.hamcrest.CoreMatchers;6import org.junit.Assert;7import org.junit.Test;8import org.junit.runner.RunWith;9import org.mockito.ArgumentMatchers;10import org.mockito.Mockito;11import org.springframework.beans.factory.annotation.Autowired;12import org.springframework.boot.test.context.SpringBootTest;13import org.springframework.boot.test.mock.mockito.MockBean;14import org.springframework.security.crypto.password.PasswordEncoder;15import org.springframework.test.context.junit4.SpringRunner;16import java.util.Collections;17@RunWith(SpringRunner.class)18@SpringBootTest19public class UserSeviceTest {20 @Autowired21 private UserSevice userSevice;22 @MockBean23 private UserRepository userRepository;24 @MockBean25 private MailSender mailSender;26 @MockBean27 private PasswordEncoder passwordEncoder;28 @Test29 public void addUser() {30 User user = new User();31 user.setEmail("some@mail.ru");32 boolean isUserCreated = userSevice.addUser(user);33 Assert.assertTrue(isUserCreated);34 Assert.assertNotNull(user.getActivationCode());35 Assert.assertTrue(CoreMatchers.is(user.getRoles()).matches(Collections.singleton(Role.USER)));36 Mockito.verify(userRepository, Mockito.times(1)).save(user);37 Mockito.verify(mailSender, Mockito.times(1))38 .send(39 ArgumentMatchers.eq(user.getEmail()),40 ArgumentMatchers.anyString(),41 ArgumentMatchers.anyString()42 );43 }44 @Test45 public void addUserFailTest() {46 User user = new User();47 user.setUsername("John");48 Mockito.doReturn(new User())49 .when(userRepository)50 .findByUsername("John");51 boolean isUserCreated = userSevice.addUser(user);52 Assert.assertFalse(isUserCreated);53 Mockito.verify(userRepository, Mockito.times(0)).save(ArgumentMatchers.any(User.class));54 Mockito.verify(mailSender, Mockito.times(0))55 .send(56 ArgumentMatchers.anyString(),57 ArgumentMatchers.anyString(),58 ArgumentMatchers.anyString()59 );60 }61 @Test62 public void activateUser() {63 User user = new User();64 user.setActivationCode("bingo!");65 Mockito.doReturn(user)66 .when(userRepository)67 .findByActivationCode("activate");68 boolean isUserActivated = userSevice.activateUser("activate");69 Assert.assertTrue(isUserActivated);70 Assert.assertNull(user.getActivationCode());71 Mockito.verify(userRepository, Mockito.times(1)).save(user);72 }73 @Test74 public void activateUserFailTest() {75 boolean isUserActivated = userSevice.activateUser("activate me");76 Assert.assertFalse(isUserActivated);77 Mockito.verify(userRepository, Mockito.times(0)).save(ArgumentMatchers.any(User.class));78 }79}...

Full Screen

Full Screen

ArgumentMatchers

Using AI Code Generation

copy

Full Screen

1package com.automationrhapsody.junitmockito;2import static org.mockito.ArgumentMatchers.anyString;3import static org.mockito.Mockito.mock;4import static org.mockito.Mockito.when;5import org.junit.Assert;6import org.junit.Test;7public class ArgumentMatchersTest {8 public void testAnyString() {9 PersonService personService = mock(PersonService.class);10 when(personService.getPerson(anyString())).thenReturn(new Person("John", "Doe"));11 Person person = personService.getPerson("123");12 Assert.assertEquals("John", person.getFirstName());13 Assert.assertEquals("Doe", person.getLastName());14 }15}

Full Screen

Full Screen

ArgumentMatchers

Using AI Code Generation

copy

Full Screen

1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3import static org.mockito.Mockito.mock;4import static org.mockito.Mockito.when;5import java.util.List;6public class 1 {7 public static void main(String[] args) {8 List mockedList = mock(List.class);9 when(mockedList.get(ArgumentMatchers.anyInt())).thenReturn("Element");10 System.out.println(mockedList.get(999));11 }12}13Mockito - ArgumentCaptor.capture()14Mockito - ArgumentCaptor.getValue()15Mockito - ArgumentCaptor.getAllValues()16Mockito - ArgumentCaptor.forClass()17Mockito - ArgumentCaptor.forClass() Example18Mockito - ArgumentCaptor.capture() Example19Mockito - ArgumentCaptor.getValue() Example20Mockito - ArgumentCaptor.getAllValues() Example21Mockito - ArgumentCaptor.match() Example22Mockito - ArgumentCaptor.verify() Example23Mockito - ArgumentCaptor.capture() Example24Mockito - ArgumentCaptor.getValue() Example25Mockito - ArgumentCaptor.getAllValues() Example26Mockito - ArgumentCaptor.match() Example27Mockito - ArgumentCaptor.verify() Example28Mockito - ArgumentCaptor.capture() Example29Mockito - ArgumentCaptor.getValue() Example30Mockito - ArgumentCaptor.getAllValues() Example31Mockito - ArgumentCaptor.match() Example32Mockito - ArgumentCaptor.verify() Example33Mockito - ArgumentCaptor.capture() Example34Mockito - ArgumentCaptor.getValue() Example35Mockito - ArgumentCaptor.getAllValues() Example36Mockito - ArgumentCaptor.match() Example37Mockito - ArgumentCaptor.verify() Example38Mockito - ArgumentCaptor.capture() Example39Mockito - ArgumentCaptor.getValue() Example40Mockito - ArgumentCaptor.getAllValues() Example41Mockito - ArgumentCaptor.match() Example42Mockito - ArgumentCaptor.verify() Example43Mockito - ArgumentCaptor.capture() Example44Mockito - ArgumentCaptor.getValue() Example45Mockito - ArgumentCaptor.getAllValues() Example46Mockito - ArgumentCaptor.match() Example47Mockito - ArgumentCaptor.verify() Example48Mockito - ArgumentCaptor.capture() Example49Mockito - ArgumentCaptor.getValue() Example50Mockito - ArgumentCaptor.getAllValues() Example51Mockito - ArgumentCaptor.match()

Full Screen

Full Screen

ArgumentMatchers

Using AI Code Generation

copy

Full Screen

1package org.mockito;2import static org.mockito.Mockito.*;3import org.mockito.ArgumentMatchers;4import org.junit.Test;5import org.junit.runner.RunWith;6import org.mockito.InjectMocks;7import org.mockito.Mock;8import org.mockito.junit.MockitoJUnitRunner;9import static org.junit.Assert.*;10import java.util.ArrayList;11import java.util.List;12@RunWith(MockitoJUnitRunner.class)13public class TestArgumentMatchers {14private List<String> mockedList;15public void testArgumentMatchers() {16mockedList = mock(List.class);17mockedList.add("one");18mockedList.clear();19verify(mockedList).add("one");20verify(mockedList).clear();21}22public void testArgumentMatchers2() {23mockedList = mock(List.class);24mockedList.add("one");25mockedList.clear();26verify(mockedList).add(anyString());27verify(mockedList).clear();28}29public void testArgumentMatchers3() {30mockedList = mock(List.class);31mockedList.add("one");32mockedList.clear();33verify(mockedList, times(1)).add(anyString());34verify(mockedList, times(1)).clear();35}36public void testArgumentMatchers4() {37mockedList = mock(List.class);38mockedList.add("one");39mockedList.clear();40verify(mockedList, times(1)).add(ArgumentMatchers.anyString());41verify(mockedList, times(1)).clear();42}43public void testArgumentMatchers5() {44mockedList = mock(List.class);45mockedList.add("one");46mockedList.clear();47verify(mockedList, times(1)).add(ArgumentMatchers.any(String.class));48verify(mockedList, times(1)).clear();49}50public void testArgumentMatchers6() {51mockedList = mock(List.class);52mockedList.add("one");53mockedList.clear();54verify(mockedList, times(1)).add(ArgumentMatchers.eq("one"));55verify(mockedList, times(1)).clear();56}57public void testArgumentMatchers7() {58mockedList = mock(List.class);59mockedList.add("one");60mockedList.clear();

Full Screen

Full Screen

ArgumentMatchers

Using AI Code Generation

copy

Full Screen

1import static org.mockito.ArgumentMatchers.anyInt;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.when;4public class 1 {5 public static void main(String[] args) {6 Adder adder = mock(Adder.class);7 when(adder.add(anyInt(), anyInt())).thenReturn(10);8 int result = adder.add(10, 20);9 System.out.println(result);10 }11}12import static org.mockito.ArgumentMatchers.any;13import static org.mockito.Mockito.mock;14import static org.mockito.Mockito.when;15public class 2 {16 public static void main(String[] args) {17 Adder adder = mock(Adder.class);18 when(adder.add(any(), any())).thenReturn(10);19 int result = adder.add(10, 20);20 System.out.println(result);21 }22}

Full Screen

Full Screen

ArgumentMatchers

Using AI Code Generation

copy

Full Screen

1packat sgatice com.automationrhapsody.juni.anyInttmockito;2import static org.mockito.Mockito.when;3public class 1 {4 public static void main(String[] args) {5 Adder adder = mock(Adder.cmpor);6 when(adder.add(anyInt(), anyInt())).thenReturn(10);7 int result = adder.add(10, 20);8 System.out.println(result);9 }10}11import static org.mockito.ArgumentMatchers.any;12import static org.mockito.Mockito.mock;13import static org.mockito.Mockito.when;14public class 2 mockito.ArgumentMatchers.anyString;15import static org.mockito.Mockito.mock;16import sAdder adder = mock(Adder.class);17 when(adder.add(any(), any())).thenReturn(10);18 int result = adder.add(10, 20);19 System.out.println(result);20 }21}22to.Mockito.when;

Full Screen

Full Screen

ArgumentMatchers

Using AI Code Generation

copy

Full Screen

1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3class TestMockito {4 public static void main(String[] args) {5import org.junit.Assert;6import org.junit.Test;7public class ArgumentMatchersTest {8 public void testAnyString() {9 PersonService personService = mock(PersonService.class);10 when(personService.getPerson(anyString())).thenReturn(new Person("John", "Doe"));11 Person person = personService.getPerson("123");12 Assert.assertEquals("John", person.getFirstName());13 Assert.assertEquals("Doe", person.getLastName());14 }15}

Full Screen

Full Screen

ArgumentMatchers

Using AI Code Generation

copy

Full Screen

1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3import java.util.List;4class Test {5public static void main(String[] args) {6List mockList = Mockito.mock(List.class);7Mockito.when(mockList.get(ArgumentMatchers.anyInt())).thenReturn("Element");8System.out.println(mockList.get(0));9System.out.println(mockList.get(1));10System.out.println(mockList.get(2));11System.out.println(mockList.get(3));12System.out.println(mockList.get(4));13System.out.println(mockList.get(5));14System.out.println(mockList.get(6));15System.out.println(mockList.get(7));16}17}18import org.mockito.ArgumentMatchers;19import org.mockito.Mockito;20import java.util.List;21class Test {22public static void main(String[] args) {23List mockList = Mockito.mock(List.class);24Mockito.when(mockList.get(ArgumentMatchers.anyInt())).thenReturn("Element");25System.out.println(mockList.get(0));26System.out.println(mockList.get(1));27System.out.println(mockList.get(2));28System.out.println(mockList.get(3));29System.out.println(mockList.get(4));30System.out.println(mockList.get(5));31System.out.println(mockList.get(6));32System.out.println(mockList.get(7));33}34}35import org.mockito.ArgumentMatchers;36import org.mockito.Mockito;37import java.util.List;38class Test {39public static void main(String[]

Full Screen

Full Screen

ArgumentMatchers

Using AI Code Generation

copy

Full Screen

1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3class TestMockito {4 public static void main(String[] args) {5 List mockedList = Mockito.mock(List.class);6 mockedList.add("one");7 mockedList.clear();8 Mockito.verify(mockedList).add(ArgumentMatchers.anyString());9 Mockito.verify(mockedList).clear();10 }11}12Mockito ArgumentCaptor.capture() in Java with Examples13Mockito ArgumentCaptor.getAllValues() in Java with Examples14Mockito ArgumentCaptor.getValue() in Java with Examples15Mockito ArgumentCaptor.forClass() in Java with Examples16Mockito ArgumentCaptor.verify() in Java with Exampl

Full Screen

Full Screen

ArgumentMatchers

Using AI Code Generation

copy

Full Screen

1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3import java.util.List;4class Test {5public static void main(String[] args) {6List mockList = Mockito.mock(List.class);7Mockito.when(mockList.get(ArgumentMatchers.anyInt())).thenReturn("Element");8System.out.println(mockList.get(0));9System.out.println(mockList.get(1));10System.out.println(mockList.get(2));11System.out.println(mockList.get(3));12System.out.println(mockList.get(4));13System.out.println(mockList.get(5));14System.out.println(mockList.get(6));15System.out.println(mockList.get(7));16}17}18import org.mockito.ArgumentMatchers;19import org.mockito.Mockito;20import java.util.List;21class Test {22public static void main(String[] args) {23List mockList = Mockito.mock(List.class);24Mockito.when(mockList.get(ArgumentMatchers.anyInt())).thenReturn("Element");25System.out.println(mockList.get(0));26System.out.println(mockList.get(1));27System.out.println(mockList.get(2));28System.out.println(mockList.get(3));29System.out.println(mockList.get(4));30System.out.println(mockList.get(5));31System.out.println(mockList.get(6));32System.out.println(mockList.get(7));33}34}35import org.mockito.ArgumentMatchers;36import org.mockito.Mockito;37import java.util.List;38class Test {39public static void main(String[]

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful