Best Mockito code snippet using org.mockito.ArgumentMatchers.anyLong
Source:ItemDaoImplTest.java
...31import static org.junit.jupiter.api.Assertions.assertNull;32import static org.junit.jupiter.api.Assertions.assertThrows;33import static org.mockito.Mockito.any;34import static org.mockito.Mockito.anyInt;35import static org.mockito.Mockito.anyLong;36import static org.mockito.Mockito.anyString;37import static org.mockito.Mockito.eq;38import static org.mockito.Mockito.times;39import static org.mockito.Mockito.verify;40import static org.mockito.Mockito.when;41@SpringBootTest42public class ItemDaoImplTest {43 @Mock44 private JdbcTemplate jdbcTemplate;45 @Mock46 private KeyHolder keyHolder;47 @Mock48 private Connection connection;49 @Mock50 private DataSource dataSource;51 @Mock52 private PreparedStatement preparedStatement;53 @Mock54 private GeneratedKeyHolderFactory generatedKeyHolderFactory;55 @InjectMocks56 private ItemDaoImpl itemDaoImpl;57 private Item item;58 private List<Item> items;59 private final Long accountId = 2L;60 @BeforeEach61 void setUp() throws SQLException {62 MockitoAnnotations.initMocks(this);63 when(this.jdbcTemplate.getDataSource()).thenReturn(dataSource);64 when(this.dataSource.getConnection()).thenReturn(this.connection);65 when(this.connection.prepareStatement(anyString(), anyInt())).thenReturn(this.preparedStatement);66 when(this.generatedKeyHolderFactory.newKeyHolder()).thenReturn(keyHolder);67 when(this.keyHolder.getKey()).thenReturn(1L);68 when(this.jdbcTemplate.update(any(PreparedStatementCreator.class), any(KeyHolder.class))).thenReturn(1);69 item = new Item();70 item.setName("Green-Apple");71 item.setAccountId(accountId);72 item.setDescription("Sweet apple");73 item.setUnit("box");74 item.setVolume(5);75 items = new ArrayList<>();76 Item trout = new Item();77 trout.setName("Fish-Trout");78 trout.setDescription("fresh trout");79 trout.setAccountId(accountId);80 trout.setUnit("box");81 trout.setActive(true);82 trout.setVolume(4);83 items.add(trout);84 Item salmon = new Item();85 salmon.setName("Fish-Salmon");86 salmon.setDescription("fresh salmon");87 salmon.setAccountId(1L);88 salmon.setUnit("box");89 trout.setActive(true);90 salmon.setVolume(5);91 items.add(salmon);92 Item catfish = new Item();93 catfish.setName("Catfish");94 catfish.setDescription("fresh salmon");95 catfish.setAccountId(3L);96 catfish.setUnit("box");97 catfish.setVolume(5);98 trout.setActive(true);99 items.add(catfish);100 }101 @Test102 public void testCreate_successFlow() {103 assertEquals(item, itemDaoImpl.addItem(item));104 assertNotNull(item.getId());105 }106 @Test107 void testCreate_omittedNotNullFields() {108 when(this.keyHolder.getKey()).thenReturn(null);109 item = new Item();110 assertThrows(CRUDException.class, () -> itemDaoImpl.addItem(item));111 }112 @Test113 void testGetItems_successFlow() {114 List<Item> newItems = new ArrayList<>();115 newItems.add(items.get(0));116 PageRequest pageable = PageRequest.of(0, 3, Sort.Direction.ASC, "id");117 when(jdbcTemplate118 .query(anyString(), ArgumentMatchers.<ItemRowMapper>any(), eq(accountId), eq(pageable.getPageSize()),119 eq(pageable.getOffset())))120 .thenReturn(newItems);121 Integer expectedCount = 1;122 List<Item> resultList = itemDaoImpl.getItems(accountId, pageable.getPageSize(), pageable.getOffset(),123 pageable.getSort());124 assertEquals(expectedCount, resultList.size());125 }126 @Test127 void testGetItems_omittedFlowNotSorted() {128 List<Item> newItems = new ArrayList<>();129 newItems.add(items.get(0));130 PageRequest pageable = PageRequest.of(0, 3);131 when(jdbcTemplate132 .query(anyString(), ArgumentMatchers.<ItemRowMapper>any(), eq(accountId), eq(pageable.getPageSize()),133 eq(pageable.getOffset())))134 .thenReturn(newItems);135 Integer expectedCount = 1;136 List<Item> resultList = itemDaoImpl.getItems(accountId, pageable.getPageSize(), pageable.getOffset(),137 pageable.getSort());138 assertEquals(expectedCount, resultList.size());139 }140 @Test141 void testGetItems_omittedFlowCRUDException() {142 PageRequest pageable = PageRequest.of(0, 3);143 when(jdbcTemplate144 .query(anyString(), ArgumentMatchers.<ItemRowMapper>any(), eq(accountId), eq(pageable.getPageSize()),145 eq(pageable.getOffset()))).thenThrow(new DataAccessException("") {146 });147 assertThrows(CRUDException.class, () -> itemDaoImpl.getItems(accountId, pageable.getPageSize(),148 pageable.getOffset(), pageable.getSort()));149 }150 @Test151 public void testCountItemsById_successFlow() {152 Integer count = 3;153 when(this.jdbcTemplate.queryForObject(anyString(), eq(Integer.class), anyLong()))154 .thenReturn(count);155 assertEquals(count, itemDaoImpl.countItemsById(accountId));156 }157 @Test158 public void testCountItemsById_omittedFlowCRUDException() {159 when(this.jdbcTemplate.queryForObject(anyString(), eq(Integer.class), anyLong()))160 .thenThrow(new DataAccessException("") {161 });162 assertThrows(CRUDException.class, () -> itemDaoImpl.countItemsById(accountId));163 }164 @Test165 public void testFindItemByName_successFlow() {166 when(jdbcTemplate.queryForObject(anyString(), ArgumentMatchers.<ItemRowMapper>any(), anyLong(),167 anyString()))168 .thenReturn(item);169 assertEquals(item, itemDaoImpl.findItemByName(item.getName(), accountId));170 }171 @Test172 public void testFindItemByName_omittedFlow() {173 when(jdbcTemplate.queryForObject(anyString(), ArgumentMatchers.<ItemRowMapper>any(), anyLong(),174 anyString())).thenThrow(new EmptyResultDataAccessException(1) {175 });176 assertNull(itemDaoImpl.findItemByName(item.getName(), accountId));177 }178 @Test179 public void testFindItemByName_omittedFlowCRUDException() {180 when(jdbcTemplate.queryForObject(anyString(), ArgumentMatchers.<ItemRowMapper>any(), anyLong(),181 anyString())).thenThrow(new DataAccessException("") {182 });183 CRUDException exception = assertThrows(CRUDException.class, () -> itemDaoImpl.findItemByName(item.getName(),184 accountId));185 assertEquals(exception.getMessage(), "Failed during `select` {name = " + item.getName() + "}");186 }187 @Test188 public void testFindItemByAccountId_successFlow() {189 when(jdbcTemplate.query(anyString(), ArgumentMatchers.<ItemRowMapper>any(), anyLong()))190 .thenReturn(items);191 assertEquals(items, itemDaoImpl.findItemByAccountId(accountId));192 }193 @Test194 public void testFindItemByAccountId_omittedFlow() {195 when(jdbcTemplate.query(anyString(), ArgumentMatchers.<ItemRowMapper>any(), anyLong()))196 .thenThrow(new EmptyResultDataAccessException(1) {197 });198 ItemNotFoundException exception =199 assertThrows(ItemNotFoundException.class, () -> itemDaoImpl.findItemByAccountId(accountId));200 assertEquals(exception.getMessage(), "Failed to get item during `select` {account_id = " + accountId + "}");201 }202 @Test203 public void testFindItemByAccountId_omittedFlowCRUDException() {204 when(jdbcTemplate.query(anyString(), ArgumentMatchers.<ItemRowMapper>any(), anyLong()))205 .thenThrow(new DataAccessException("") {206 });207 CRUDException exception = assertThrows(CRUDException.class, () -> itemDaoImpl.findItemByAccountId(accountId));208 assertEquals(exception.getMessage(), "Failed during `select` {account_id = " + accountId + "}");209 }210 @Test211 void findItemById_successFlow() {212 Long itemId = 2L;213 when(jdbcTemplate.queryForObject(anyString(), ArgumentMatchers.<ItemRowMapper>any(), anyLong(),214 anyLong())).thenReturn(item);215 assertEquals(item, itemDaoImpl.findItemById(itemId, accountId));216 }217 @Test218 void findItemById_omittedFlow() {219 Long itemId = 2L;220 when(jdbcTemplate.queryForObject(anyString(), ArgumentMatchers.<ItemRowMapper>any(), anyLong(),221 anyLong())).thenThrow(new EmptyResultDataAccessException(1) {222 });223 ItemNotFoundException exception =224 assertThrows(ItemNotFoundException.class, () -> itemDaoImpl.findItemById(itemId,225 accountId));226 assertEquals(exception.getMessage(), "Failed to get item during `select` {id = " + itemId + "}");227 }228 @Test229 void findItemById_omittedFlowCRUDException() {230 Long itemId = 2L;231 when(jdbcTemplate.queryForObject(anyString(), ArgumentMatchers.<ItemRowMapper>any(), anyLong(),232 anyLong())).thenThrow(new DataAccessException("") {233 });234 CRUDException exception = assertThrows(CRUDException.class, () -> itemDaoImpl.findItemById(itemId,235 accountId));236 assertEquals(exception.getMessage(), "Failed during `select` {id = " + itemId + "}");237 }238 @Test239 void findItemsById_successFlow() {240 String ids = "1, 4, 8";241 when(jdbcTemplate.query(anyString(), ArgumentMatchers.<ItemRowMapper>any(), anyLong()))242 .thenReturn(items);243 assertEquals(items, itemDaoImpl.findItemsById(ids, accountId));244 }245 @Test246 void findItemsById_omittedFlow() {247 String ids = "1, 4, 8";248 when(jdbcTemplate.query(anyString(), ArgumentMatchers.<ItemRowMapper>any(), anyLong()))249 .thenThrow(new EmptyResultDataAccessException(1) {250 });251 ItemNotFoundException exception = assertThrows(ItemNotFoundException.class, () -> itemDaoImpl.findItemsById(ids,252 accountId));253 assertEquals(exception.getMessage(), "Failed to get item during `select` {id = " + ids + "}");254 }255 @Test256 void findItemsById_omittedFlowCRUDException() {257 String ids = "1, 4, 8";258 when(jdbcTemplate.query(anyString(), ArgumentMatchers.<ItemRowMapper>any(), anyLong()))259 .thenThrow(new DataAccessException("") {260 });261 CRUDException exception = assertThrows(CRUDException.class, () -> itemDaoImpl.findItemsById(ids,262 accountId));263 assertEquals(exception.getMessage(), "Failed during `select` {id = " + ids + "}");264 }265 @Test266 void isExistItemById_successFlow() {267 Long itemId = 2L;268 when(jdbcTemplate.queryForObject(anyString(), ArgumentMatchers.<RowMapper<Boolean>>any(), anyLong(),269 anyLong())).thenReturn(true);270 assertEquals(true, itemDaoImpl.isExistItemById(itemId, accountId));271 }272 @Test273 void isExistItemById_omittedFlow() {274 Long itemId = 2L;275 when(jdbcTemplate.queryForObject(anyString(), ArgumentMatchers.<RowMapper<Boolean>>any(), anyLong(),276 anyLong())).thenThrow(new EmptyResultDataAccessException(1) {277 });278 ItemNotFoundException exception = assertThrows(ItemNotFoundException.class,279 () -> itemDaoImpl.isExistItemById(itemId,280 accountId));281 assertEquals(exception.getMessage(), "Failed to get item during `select` {id = " + itemId + "}");282 }283 @Test284 void isExistItemById_omittedFlowCRUDException() {285 Long itemId = 2L;286 when(jdbcTemplate.queryForObject(anyString(), ArgumentMatchers.<RowMapper<Boolean>>any(), anyLong(),287 anyLong())).thenThrow(new DataAccessException("") {288 });289 CRUDException exception = assertThrows(CRUDException.class,290 () -> itemDaoImpl.isExistItemById(itemId,291 accountId));292 assertEquals(exception.getMessage(), "Failed during `select` {id = " + itemId + "}");293 }294 @Test295 void softDeleteItem_successFlow() {296 Long itemId = 2L;297 when(jdbcTemplate.update(anyString(), eq(false), anyLong(),298 anyLong())).thenReturn(1);299 assertEquals(true, itemDaoImpl.softDeleteItem(itemId, accountId));300 }301 @Test302 void softDeleteItem_omittedFlow() {303 Long itemId = 2L;304 when(jdbcTemplate.update(anyString(), eq(false), anyLong(),305 anyLong())).thenReturn(0);306 assertThrows(ItemNotFoundException.class,307 () -> itemDaoImpl.softDeleteItem(itemId, accountId));308 }309 @Test310 void softDeleteItem_omittedFlowCRUDException() {311 Long itemId = 2L;312 when(jdbcTemplate.update(anyString(), eq(false), anyLong(),313 anyLong())).thenThrow(new DataAccessException("") {314 });315 CRUDException exception =316 assertThrows(CRUDException.class, () -> itemDaoImpl.softDeleteItem(itemId, accountId));317 assertEquals("Error during soft `delete` {name = " + itemId + "}", exception.getMessage());318 }319 @Test320 void hardDeleteItem_successFlow() {321 when(jdbcTemplate.update(anyString(), anyLong())).thenReturn(1);322 itemDaoImpl.hardDelete(accountId);323 verify(jdbcTemplate, times(1)).update(anyString(), eq(accountId));324 }325 @Test326 void hardDeleteItem_omittedFlowCRUDException() {327 when(jdbcTemplate.update(anyString(), anyLong())).thenThrow(new DataAccessException("") {328 });329 CRUDException exception = assertThrows(CRUDException.class, () -> itemDaoImpl.hardDelete(accountId));330 assertEquals("Error during hard `delete` item {accountId = " + accountId + "}", exception.getMessage());331 }332 @Test333 void findItemsByNameQuery_successFlow() {334 String query = "Fish";335 when(jdbcTemplate.query(anyString(), ArgumentMatchers.<ItemRowMapper>any(), anyString(), anyLong()))336 .thenReturn(items);337 assertEquals(items, itemDaoImpl.findItemsByNameQuery(query, accountId));338 }339 @Test340 void findItemsByNameQuery_omittedFlowCRUDException() {341 String query = "Fish";342 when(jdbcTemplate.query(anyString(), ArgumentMatchers.<ItemRowMapper>any(), anyString(), anyLong()))343 .thenThrow(new DataAccessException("") {344 });345 assertThrows(CRUDException.class, () -> itemDaoImpl.findItemsByNameQuery(query, accountId));346 }347 @Test348 void updateItem_successFlow() {349 item.setId(1L);350 when(jdbcTemplate.update(anyString(), anyString(), anyString(), anyString(), anyInt(), anyLong(),351 anyLong())).thenReturn(1);352 assertEquals(item, itemDaoImpl.updateItem(item));353 }354 @Test355 void updateItem_omittedFlow() {356 item.setId(1L);357 when(jdbcTemplate.update(anyString(), anyString(), anyString(), anyString(), anyInt(), anyLong(),358 anyLong())).thenReturn(0);359 ItemNotFoundException exception = assertThrows(ItemNotFoundException.class, () -> itemDaoImpl.updateItem(item));360 assertEquals("Failed to get item during `update` {id" + item.getId() + "}", exception.getMessage());361 }362 @Test363 void updateItem_omittedFlowCRUDException() {364 item.setId(1L);365 when(jdbcTemplate.update(anyString(), anyString(), anyString(), anyString(), anyInt(), anyLong(),366 anyLong())).thenThrow(new DataAccessException("") {367 });368 CRUDException exception = assertThrows(CRUDException.class, () -> itemDaoImpl.updateItem(item));369 assertEquals("Error during `update` {id " + item.getId() + "}", exception.getMessage());370 }371}...
Source:ClockDriftSafeMonitorSchedulerTest.java
...131 return null;132 });133 return createDummyFuture();134 }135 }).when(cronScheduler).scheduleAtFixedRate(ArgumentMatchers.anyLong(), ArgumentMatchers.anyLong(),136 ArgumentMatchers.any(), ArgumentMatchers.any(CronTask.class));137 Monitor monitor = Mockito.mock(Monitor.class);138 MonitorSchedulerConfig config = Mockito.mock(MonitorSchedulerConfig.class);139 Mockito.when(config.getEmitterPeriod()).thenReturn(new org.joda.time.Duration(1000L));140 final MonitorScheduler scheduler = new ClockDriftSafeMonitorScheduler(141 config,142 Mockito.mock(ServiceEmitter.class),143 ImmutableList.of(monitor),144 cronScheduler,145 executor146 );147 scheduler.start();148 latch.await(5, TimeUnit.SECONDS);149 Mockito.verify(monitor, Mockito.times(1)).start();150 Mockito.verify(cronScheduler, Mockito.times(1)).scheduleAtFixedRate(ArgumentMatchers.anyLong(),151 ArgumentMatchers.anyLong(),152 ArgumentMatchers.any(), ArgumentMatchers.any(CronTask.class));153 Mockito.verify(executor, Mockito.times(2)).submit(ArgumentMatchers.any(Callable.class));154 Mockito.verify(monitor, Mockito.times(2)).monitor(ArgumentMatchers.any());155 scheduler.stop();156 }157 158 @Test159 public void testStart_RepeatAndStopScheduling() throws InterruptedException160 {161 ExecutorService executor = Mockito.mock(ExecutorService.class);162 CountDownLatch latch = new CountDownLatch(1);163 Mockito.doAnswer(new Answer<Future<?>>()164 {165 private int scheduleCount = 0;166 @SuppressWarnings("unchecked")167 @Override168 public Future<?> answer(InvocationOnMock invocation)169 {170 final Object originalArgument = (invocation.getArguments())[3];171 CronTask task = ((CronTask) originalArgument);172 Mockito.doAnswer(new Answer<Future<?>>()173 {174 @Override175 public Future<Boolean> answer(InvocationOnMock invocation) throws Exception176 {177 final Object originalArgument = (invocation.getArguments())[0];178 ((Callable<Boolean>) originalArgument).call();179 return CompletableFuture.completedFuture(Boolean.FALSE);180 }181 }).when(executor).submit(ArgumentMatchers.any(Callable.class));182 cronTaskRunner.submit(() -> {183 while (scheduleCount < 2) {184 scheduleCount++;185 task.run(123L);186 }187 latch.countDown();188 return null;189 });190 return createDummyFuture();191 }192 }).when(cronScheduler).scheduleAtFixedRate(ArgumentMatchers.anyLong(), ArgumentMatchers.anyLong(),193 ArgumentMatchers.any(), ArgumentMatchers.any(CronTask.class));194 Monitor monitor = Mockito.mock(Monitor.class);195 MonitorSchedulerConfig config = Mockito.mock(MonitorSchedulerConfig.class);196 Mockito.when(config.getEmitterPeriod()).thenReturn(new org.joda.time.Duration(1000L));197 final MonitorScheduler scheduler = new ClockDriftSafeMonitorScheduler(198 config,199 Mockito.mock(ServiceEmitter.class),200 ImmutableList.of(monitor),201 cronScheduler,202 executor203 );204 scheduler.start();205 latch.await(5, TimeUnit.SECONDS);206 Mockito.verify(monitor, Mockito.times(1)).start();207 Mockito.verify(cronScheduler, Mockito.times(1)).scheduleAtFixedRate(ArgumentMatchers.anyLong(),208 ArgumentMatchers.anyLong(),209 ArgumentMatchers.any(), ArgumentMatchers.any(CronTask.class));210 Mockito.verify(executor, Mockito.times(1)).submit(ArgumentMatchers.any(Callable.class));211 Mockito.verify(monitor, Mockito.times(1)).monitor(ArgumentMatchers.any());212 Mockito.verify(monitor, Mockito.times(1)).stop();213 scheduler.stop();214 }215 216 @Test217 public void testStart_UnexpectedExceptionWhileMonitoring() throws InterruptedException218 {219 ExecutorService executor = Mockito.mock(ExecutorService.class);220 Monitor monitor = Mockito.mock(Monitor.class);221 Mockito.when(monitor.monitor(ArgumentMatchers.any(ServiceEmitter.class)))222 .thenThrow(new RuntimeException("Test throwing exception while monitoring"));223 MonitorSchedulerConfig config = Mockito.mock(MonitorSchedulerConfig.class);224 Mockito.when(config.getEmitterPeriod()).thenReturn(new org.joda.time.Duration(1000L));225 CountDownLatch latch = new CountDownLatch(1);226 AtomicBoolean monitorResultHolder = new AtomicBoolean(false);227 Mockito.doAnswer(new Answer<Future<?>>()228 {229 @SuppressWarnings("unchecked")230 @Override231 public Future<?> answer(InvocationOnMock invocation)232 {233 final Object originalArgument = (invocation.getArguments())[3];234 CronTask task = ((CronTask) originalArgument);235 Mockito.doAnswer(new Answer<Future<?>>()236 {237 @Override238 public Future<Boolean> answer(InvocationOnMock invocation) throws Exception239 {240 final Object originalArgument = (invocation.getArguments())[0];241 final boolean continueMonitor = ((Callable<Boolean>) originalArgument).call();242 monitorResultHolder.set(continueMonitor);243 return CompletableFuture.completedFuture(continueMonitor);244 }245 }).when(executor).submit(ArgumentMatchers.any(Callable.class));246 cronTaskRunner.submit(() -> {247 task.run(123L);248 latch.countDown();249 return null;250 });251 return createDummyFuture();252 }253 }).when(cronScheduler).scheduleAtFixedRate(ArgumentMatchers.anyLong(), ArgumentMatchers.anyLong(),254 ArgumentMatchers.any(), ArgumentMatchers.any(CronTask.class));255 256 final MonitorScheduler scheduler = new ClockDriftSafeMonitorScheduler(257 config,258 Mockito.mock(ServiceEmitter.class),259 ImmutableList.of(monitor),260 cronScheduler,261 executor262 );263 scheduler.start();264 latch.await(5, TimeUnit.SECONDS);265 Mockito.verify(monitor, Mockito.times(1)).start();266 Mockito.verify(cronScheduler, Mockito.times(1)).scheduleAtFixedRate(ArgumentMatchers.anyLong(),267 ArgumentMatchers.anyLong(),268 ArgumentMatchers.any(), ArgumentMatchers.any(CronTask.class));269 Mockito.verify(executor, Mockito.times(1)).submit(ArgumentMatchers.any(Callable.class));270 Mockito.verify(monitor, Mockito.times(1)).monitor(ArgumentMatchers.any());271 Assert.assertTrue(monitorResultHolder.get());272 scheduler.stop();273 }274 275 @Test276 public void testStart_UnexpectedExceptionWhileScheduling() throws InterruptedException277 {278 ExecutorService executor = Mockito.mock(ExecutorService.class);279 Monitor monitor = Mockito.mock(Monitor.class);280 MonitorSchedulerConfig config = Mockito.mock(MonitorSchedulerConfig.class);281 Mockito.when(config.getEmitterPeriod()).thenReturn(new org.joda.time.Duration(1000L));282 CountDownLatch latch = new CountDownLatch(1);283 Mockito.doAnswer(new Answer<Future<?>>()284 {285 @SuppressWarnings("unchecked")286 @Override287 public Future<?> answer(InvocationOnMock invocation)288 {289 final Object originalArgument = (invocation.getArguments())[3];290 CronTask task = ((CronTask) originalArgument);291 Mockito.when(executor.submit(ArgumentMatchers.any(Callable.class)))292 .thenThrow(new RuntimeException("Test throwing exception while scheduling"));293 cronTaskRunner.submit(() -> {294 task.run(123L);295 latch.countDown();296 return null;297 });298 return createDummyFuture();299 }300 }).when(cronScheduler).scheduleAtFixedRate(ArgumentMatchers.anyLong(), ArgumentMatchers.anyLong(),301 ArgumentMatchers.any(), ArgumentMatchers.any(CronTask.class));302 303 final MonitorScheduler scheduler = new ClockDriftSafeMonitorScheduler(304 config,305 Mockito.mock(ServiceEmitter.class),306 ImmutableList.of(monitor),307 cronScheduler,308 executor309 );310 scheduler.start();311 latch.await(5, TimeUnit.SECONDS);312 Mockito.verify(monitor, Mockito.times(1)).start();313 Mockito.verify(cronScheduler, Mockito.times(1)).scheduleAtFixedRate(ArgumentMatchers.anyLong(),314 ArgumentMatchers.anyLong(),315 ArgumentMatchers.any(), ArgumentMatchers.any(CronTask.class));316 Mockito.verify(executor, Mockito.times(1)).submit(ArgumentMatchers.any(Callable.class));317 scheduler.stop();318 }319 320 private Future createDummyFuture()321 {322 Future<?> future = new Future()323 {324 @Override325 public boolean cancel(boolean mayInterruptIfRunning)326 {327 return false;328 }...
Source:CommentServiceTest.java
...111 }112 113 @Test114 public void should_return_create_comment() throws Exception {115 Mockito.when(userRepository.findById(ArgumentMatchers.anyLong())).thenReturn(Optional.of(user));116 Mockito.when(storyRepository.findById(ArgumentMatchers.anyLong())).thenReturn(Optional.of(story));117 Mockito.when(commentRepository.save(ArgumentMatchers.any(Comment.class))).thenReturn(comment);118 Mockito.when(loveRepository.countByStoryId(ArgumentMatchers.anyLong())).thenReturn(23l);119 120 Assert.assertEquals(commentService.createComment(commentRequest, userPrincipal, story.getId()).getBody(), comment.getBody());121 }122 @Test123 public void should_return_delete_comment() throws Exception {124 Mockito.when(commentRepository.findById(ArgumentMatchers.any(Long.class125 ))).thenReturn(Optional.of(comment));126 Mockito.when(userRepository.findById(ArgumentMatchers.anyLong())).thenReturn(Optional.of(user));127 Assert.assertEquals(commentService.deleteComment(comment.getId(), userPrincipal).hasBody(), apiResponse.getSuccess());128 }129 @Test130 public void should_return_getCommentById() throws Exception {131 Mockito.when(commentRepository.findById(ArgumentMatchers.anyLong())).thenReturn(Optional.of(comment));132 Mockito.when(userRepository.findById(ArgumentMatchers.anyLong())).thenReturn(Optional.of(user));133 Mockito.when(loveRepository.countByStoryId(ArgumentMatchers.anyLong())).thenReturn(12l);134 Assert.assertEquals(commentService.getCommentById(comment.getId()).getBody(), comment.getBody());135 Assert.assertEquals(commentService.getCommentById(comment.getId()).getCreatedBy().getId(), comment.getCreatedBy());136 Assert.assertEquals(commentService.getCommentById(comment.getId()).getStoryResponse().getDescription(), comment.getStory().getDescription());137 }138 @Test139 public void should_return_getAllComment() throws Exception {140 Mockito.when(commentRepository.findAll(ArgumentMatchers.isA(Pageable.class))).thenReturn(page);141 Mockito.when(userRepository.findByIdIn(ArgumentMatchers.any(List.class))).thenReturn(creators);142 Mockito.when(userRepository.findById(ArgumentMatchers.anyLong())).thenReturn(Optional.of(user));143 Mockito.when(loveRepository.countByStoryId(ArgumentMatchers.anyLong())).thenReturn(12l);144 Assert.assertTrue(commentService.getAllComment(0, 10).getContent().get(0).getBody().contains(comment.getBody()));145 Assert.assertTrue(commentService.getAllComment(0, 10).getContent().get(0).getCreatedBy().getUsername().contains(user.getUsername()));146 Assert.assertTrue(commentService.getAllComment(0, 10).getContent().get(0).getStoryResponse().getBody().contains(story.getBody()));147 }148 @Test149 public void should_return_getCommentsByUserId() throws Exception {150 Mockito.when(userRepository.findById(ArgumentMatchers.anyLong())).thenReturn(Optional.of(user));151 Mockito.when(commentRepository.findByUserId(ArgumentMatchers.anyLong(), ArgumentMatchers.isA(Pageable.class))).thenReturn(page);152 Mockito.when(userRepository.findById(ArgumentMatchers.anyLong())).thenReturn(Optional.of(user));153 Mockito.when(loveRepository.countByStoryId(ArgumentMatchers.anyLong())).thenReturn(123l);154 Assert.assertTrue(commentService.getCommentsByUserId(user.getId(), 0, 10).getContent().get(0).getBody().contains(comment.getBody()));155 Assert.assertTrue(commentService.getCommentsByUserId(user.getId(), 0, 10).getContent().get(0).getStoryResponse().getBody().contains(story.getBody()));156 Assert.assertTrue(commentService.getCommentsByUserId(user.getId(), 0, 10).getContent().get(0).getCreatedBy().getUsername().contains(user.getUsername()));157 }158 @Test159 public void should_return_getCommentsByStoryId() throws Exception {160 Mockito.when(commentRepository.findByStoryId(ArgumentMatchers.anyLong(), ArgumentMatchers.isA(Pageable.class))).thenReturn(page);161 Mockito.when(userRepository.findByIdIn(ArgumentMatchers.anyList())).thenReturn(creators);162 Mockito.when(userRepository.findById(ArgumentMatchers.anyLong())).thenReturn(Optional.of(user));163 Mockito.when(loveRepository.countByStoryId(ArgumentMatchers.anyLong())).thenReturn(123l);164 Assert.assertTrue(commentService.getCommentsByStoryId(story.getId(), 0, 10).getContent().get(0).getBody().contains(comment.getBody()));165 Assert.assertTrue(commentService.getCommentsByStoryId(story.getId(), 0, 10).getContent().get(0).getId().equals(comment.getId()));166 Assert.assertTrue(commentService.getCommentsByStoryId(story.getId(), 0, 10).getContent().get(0).getStoryResponse().getDescription().contains(story.getDescription()));167 }168 @Test169 public void should_return_getCommentsByCreatedBy() throws Exception {170 Mockito.when(userRepository.findByUsername(ArgumentMatchers.anyString())).thenReturn(Optional.of(user));171 Mockito.when(commentRepository.findByUserId(ArgumentMatchers.anyLong(), ArgumentMatchers.isA(Pageable.class))).thenReturn(page);172 Mockito.when(userRepository.findById(ArgumentMatchers.anyLong())).thenReturn(Optional.of(user));173 Mockito.when(loveRepository.countByStoryId(ArgumentMatchers.anyLong())).thenReturn(123l);174 Assert.assertTrue(commentService.getCommentsByCreatedBy(user.getUsername(), 0, 10).getContent().get(0).getBody().contains(comment.getBody()));175 Assert.assertTrue(commentService.getCommentsByCreatedBy(user.getUsername(), 0, 10).getContent().get(0).getId().equals(comment.getId()));176 Assert.assertTrue(commentService.getCommentsByCreatedBy(user.getUsername(), 0, 10).getContent().get(0).getStoryResponse().getDescription().contains(story.getDescription()));177 }178 @Test179 public void should_return_updateComment() throws Exception {180 Mockito.when(commentRepository.findById(ArgumentMatchers.anyLong())).thenReturn(Optional.of(comment));181 Mockito.when(userRepository.findById(ArgumentMatchers.anyLong())).thenReturn(Optional.of(user));182 Mockito.when(storyRepository.findById(ArgumentMatchers.anyLong())).thenReturn(Optional.of(story));183 Mockito.when(commentRepository.save(ArgumentMatchers.any(Comment.class))).thenReturn(updatedComment);184 Mockito.when(userRepository.findById(ArgumentMatchers.any(Long.class))).thenReturn(Optional.of(user));185 Mockito.when(loveRepository.countByStoryId(ArgumentMatchers.anyLong())).thenReturn(124L);186 Assert.assertTrue(commentService.updateComment(updatedCommentRequest, comment.getId(), story.getId(), userPrincipal).getId().equals(updatedComment.getId()));187 Assert.assertTrue(commentService.updateComment(updatedCommentRequest, comment.getId(), story.getId(), userPrincipal).getCreatedBy().getUsername().contains(user.getUsername()));188 Assert.assertTrue(commentService.updateComment(updatedCommentRequest, comment.getId(), story.getId(), userPrincipal).getBody().contains(updatedComment.getBody()));189 }190}...
Source:CalculationProcessorBTest.java
...53 this.calculationProcessorB.init();54 calcJob = SchedularTestUtil.createMockCalcJob();55 }56 @Test public void testCalculationProcessorBSuccess() throws Exception {57 when(this.assetDataRespository.findAllByDataTimestampBetween(ArgumentMatchers.anyLong(), ArgumentMatchers.anyLong(),58 ArgumentMatchers.anyString(),ArgumentMatchers.anyLong())).thenReturn(59 SchedularTestUtil.createMockAssetDataTimestamp());60 when(this.calculationConfigMasterRepository.findByAssetTypeId(ArgumentMatchers.anyString()))61 .thenReturn(SchedularTestUtil.createMockCalculationConfigMasterDO());62 when(this.assetDataRespository.findAllByAssetNameTimestamp(ArgumentMatchers.anyString(),63 ArgumentMatchers.anyLong(), ArgumentMatchers.anyLong()))64 .thenReturn(SchedularTestUtil.createMockAssetDataParamDTOList());65 Asset a = new Asset();66 a.setAssetTypeId("aks");67 a.setParentAssetId(a);68 a.setId("akxsjxs");69 a.setName("dummy");70 Optional<Asset> asset = Optional.of(a);71 when(this.IUOMService.getUOMConversionData(ArgumentMatchers.any(UOMReqDTO.class)))72 .thenReturn(SchedularTestUtil.createMockUOMRespDTO());73 when(this.assetRepository.findById(ArgumentMatchers.anyString())).thenReturn(asset);74 when(this.assetParamRepository.findByUnit(ArgumentMatchers.anyString()))75 .thenReturn(SchedularTestUtil.createMockAssetParams());76 when(this.calculationService.getCalculatedData(ArgumentMatchers.any(CalcEngineDTO.class)))77 .thenReturn(new ArrayList<>(Arrays.asList(SchedularTestUtil.createMockInput())));78 ApiResponseDTO apiResponse = calculationProcessorB.process(calcJob);79 assertNotEquals(null, apiResponse);80 }81 @Test82 public void testCalculationProcessorBSuccess2() throws Exception { //83 when(this.assetDataRespository.findAllByDataTimestampBetween(ArgumentMatchers.anyLong(),84 ArgumentMatchers.anyLong(), //85 ArgumentMatchers.anyString(), ArgumentMatchers.anyLong()))86 .thenReturn(SchedularTestUtil.createMockAssetDataTimestamp()); //87 when(this.calculationConfigMasterRepository.findByAssetTypeId(ArgumentMatchers.anyString()))88 .thenReturn(SchedularTestUtil.createMockCalculationConfigMasterDO());89 when(this.assetDataRespository.findAllByAssetNameTimestamp(ArgumentMatchers.anyString(),90 ArgumentMatchers.anyLong(), ArgumentMatchers.anyLong())) //91 .thenReturn(SchedularTestUtil.createMockAssetDataParamDTOList2());92 Asset a = new Asset();93 a.setAssetTypeId("aks");94 a.setParentAssetId(a);95 a.setId("akxsjxs");96 a.setName("dummy");97 Optional<Asset> asset = Optional.of(a);98 when(this.assetRepository.findById(ArgumentMatchers.anyString())).thenReturn(asset);99 when(this.assetParamRepository.findByUnit(ArgumentMatchers.anyString()))100 .thenReturn(SchedularTestUtil.createMockAssetParams());101 ApiResponseDTO apiResponse = new ApiResponseDTO();102 apiResponse = calculationProcessorB.process(calcJob);103 assertNotEquals(null, apiResponse);104 when(this.unitOfMeasureRepository.findAllUom()).thenReturn(SchedularTestUtil.createMockUnitOfMeasureDOList2());105 this.calculationProcessorB.init();106 apiResponse = calculationProcessorB.process(calcJob);107 assertNotEquals(null, apiResponse);108 }109 @Test110 public void testCalculationProcessorBException() throws Exception {111 CalcJob c = new CalcJob();112 c.setId(null);113 c.setFromDate(null);114 ApiResponseDTO apiResponse = calculationProcessorB.process(c);115 assertNotEquals(null, apiResponse);116 ApiResponseDTO apiResponse2 = calculationProcessorB.process(null);117 assertEquals(null, apiResponse2.getAssetId());118 when(this.assetDataRespository.findAllByAssetNameTimestamp(ArgumentMatchers.anyString(),119 ArgumentMatchers.anyLong(), ArgumentMatchers.anyLong())).thenReturn(Collections.emptyList());120 when(this.assetDataRespository.findAllByDataTimestampBetween(ArgumentMatchers.anyLong(),121 ArgumentMatchers.anyLong(), ArgumentMatchers.anyString(), ArgumentMatchers.anyLong()))122 .thenReturn(SchedularTestUtil.createMockAssetDataTimestamp());123 when(this.calculationConfigMasterRepository.findByAssetTypeId(ArgumentMatchers.anyString()))124 .thenReturn(SchedularTestUtil.createMockCalculationConfigMasterDO());125 ApiResponseDTO apiResponse3 = calculationProcessorB.process(calcJob);126 assertEquals(null, apiResponse3.getAssetId());127 when(this.assetDataRespository.findAllByAssetNameTimestamp(ArgumentMatchers.anyString(),128 ArgumentMatchers.anyLong(), ArgumentMatchers.anyLong()))129 .thenReturn(SchedularTestUtil.createMockAssetDataParamDTOList());130 when(this.assetParamRepository.findByUnit(ArgumentMatchers.anyString())).thenReturn(null);131 ApiResponseDTO apiResponse4 = calculationProcessorB.process(calcJob);132 assertEquals(null, apiResponse4.getAssetId());133 Asset a = new Asset();134 a.setAssetTypeId("aks");135 a.setParentAssetId(a);136 a.setId("akxsjxs");137 a.setName("dummy");138 Optional<Asset> asset = Optional.of(a);139 when(this.assetRepository.findById(ArgumentMatchers.anyString())).thenReturn(asset);140 when(this.assetParamRepository.findByUnit(ArgumentMatchers.anyString()))141 .thenReturn(SchedularTestUtil.createMockAssetParams());142 ApiResponseDTO apiResponse5 = calculationProcessorB.process(calcJob);...
Source:MockitoAnyIncorrectPrimitiveTypeTest.java
...62 "Test.java",63 "package org.mockito;",64 "import static org.mockito.ArgumentMatchers.any;",65 "import static org.mockito.ArgumentMatchers.anyFloat;",66 "import static org.mockito.ArgumentMatchers.anyLong;",67 "import static org.mockito.Mockito.mock;",68 "import static org.mockito.Mockito.when;",69 "class Test {",70 " public void test() {",71 " Foo foo = mock(Foo.class);",72 " when(foo.runWithInt(anyFloat())).thenReturn(5);",73 " when(foo.runWithBoth(any(String.class), anyLong())).thenReturn(5);",74 " }",75 " static class Foo {",76 " int run(String arg) {",77 " return 42;",78 " }",79 " int runWithInt(float arg) {",80 " return 42;",81 " }",82 " int runWithBoth(String arg1, long arg2) {",83 " return 42;",84 " }",85 " }",86 "}")87 .doTest();88 }89 @Test90 public void testPositivesSubclass() {91 compilationHelper92 .addSourceLines(93 "Test.java",94 "package org.mockito;",95 "import static org.mockito.Mockito.mock;",96 "import static org.mockito.Mockito.when;",97 "import static org.mockito.Mockito.any;",98 "import static org.mockito.Mockito.anyInt;",99 "class Test {",100 " public void test() {",101 " Foo foo = mock(Foo.class);",102 " // BUG: Diagnostic contains:",103 " when(foo.run(anyInt())).thenReturn(5);",104 " // BUG: Diagnostic contains:",105 " when(foo.runWithBoth(any(String.class), anyInt())).thenReturn(5);",106 " }",107 " static class Foo {",108 " int run(long arg) {",109 " return 42;",110 " }",111 " int runWithBoth(String arg1, float arg2) {",112 " return 42;",113 " }",114 " }",115 "}")116 .doTest();117 }118 @Test119 public void testRefactoring() {120 refactoringHelper121 .addInputLines(122 "Test.java",123 "import static org.mockito.ArgumentMatchers.any;",124 "import static org.mockito.ArgumentMatchers.anyInt;",125 "import static org.mockito.Mockito.mock;",126 "import static org.mockito.Mockito.when;",127 "class Test {",128 " public void test() {",129 " Foo foo = mock(Foo.class);",130 " when(foo.run(anyInt())).thenReturn(5);",131 " when(foo.runWithBoth(any(String.class), anyInt())).thenReturn(5);",132 " }",133 " static class Foo {",134 " int run(float arg) {",135 " return 42;",136 " }",137 " int runWithBoth(String arg1, long arg2) {",138 " return 42;",139 " }",140 " }",141 "}")142 .addOutputLines(143 "Test.java",144 "import static org.mockito.ArgumentMatchers.any;",145 "import static org.mockito.ArgumentMatchers.anyFloat;",146 "import static org.mockito.ArgumentMatchers.anyInt;",147 "import static org.mockito.ArgumentMatchers.anyLong;",148 "import static org.mockito.Mockito.mock;",149 "import static org.mockito.Mockito.when;",150 "class Test {",151 " public void test() {",152 " Foo foo = mock(Foo.class);",153 " when(foo.run(anyFloat())).thenReturn(5);",154 " when(foo.runWithBoth(any(String.class), anyLong())).thenReturn(5);",155 " }",156 " static class Foo {",157 " int run(float arg) {",158 " return 42;",159 " }",160 " int runWithBoth(String arg1, long arg2) {",161 " return 42;",162 " }",163 " }",164 "}")165 .doTest();166 }167}...
Source:TimelineManagerTest.java
...32import io.reactivex.Completable;33import io.reactivex.Flowable;34import okhttp3.HttpUrl;35import static org.mockito.ArgumentMatchers.any;36import static org.mockito.ArgumentMatchers.anyLong;37import static org.mockito.ArgumentMatchers.anyString;38import static org.mockito.Mockito.times;39import static org.mockito.Mockito.verify;40import static org.mockito.Mockito.when;41@RunWith(MockitoJUnitRunner.class)42public class TimelineManagerTest {43 @NonNull private static final HttpUrl TEST_URL =44 Objects.requireNonNull(HttpUrl.parse("https://plex.tv"));45 @Mock MusicController mockMusicController;46 @Mock QueueManager mockQueueManager;47 @Mock MediaService mockMedia;48 private TimelineManager timelineManager;49 @Before public void setup() {50 timelineManager = new TimelineManager(mockMusicController, mockQueueManager, mockMedia,51 Rx.test());52 when(mockMusicController.progress()).thenReturn(testProgress());53 when(mockMusicController.state()).thenReturn(testState());54 when(mockQueueManager.queue()).thenReturn(testQueue());55 }56 @Test public void sendRegularTimelineUpdates() {57 when(mockMedia.timeline(any(HttpUrl.class), anyLong(), anyString(), anyString(), anyString(),58 anyLong(), anyLong()))59 .thenReturn(Completable.complete());60 timelineManager.start();61 verify(mockMedia, times(1))62 .timeline(TEST_URL, 100, "key", "ratingKey", "playing", 35000, 0);63 verify(mockMedia, times(1))64 .timeline(TEST_URL, 100, "key", "ratingKey", "playing", 35000, 10000);65 verify(mockMedia, times(1))66 .timeline(TEST_URL, 100, "key", "ratingKey", "playing", 35000, 20000);67 verify(mockMedia, times(1))68 .timeline(TEST_URL, 100, "key", "ratingKey", "playing", 35000, 30000);69 }70 @Test public void keepSendingUpdatesAfterTimelineError() {71 when(mockMedia.timeline(any(HttpUrl.class), anyLong(), anyString(), anyString(), anyString(),72 anyLong(), anyLong()))73 .thenReturn(Completable.complete())74 .thenReturn(Completable.error(new IOException()))75 .thenReturn(Completable.error(new IOException()))76 .thenReturn(Completable.complete());77 timelineManager.start();78 verify(mockMedia, times(4)).timeline(any(HttpUrl.class), anyLong(), anyString(), anyString(),79 anyString(), anyLong(), anyLong());80 }81 private Flowable<Pair<List<Track>, Integer>> testQueue() {82 return Flowable.just(new Pair<>(Collections.singletonList(createTrack()), 0));83 }84 private Flowable<Integer> testState() {85 return Flowable.just(PlaybackStateCompat.STATE_PLAYING);86 }87 private Flowable<Long> testProgress() {88 return Flowable.rangeLong(0, 35)89 .map(second -> second * 1000)90 .onBackpressureBuffer();91 }92 private Track createTrack() {93 return Track.builder()...
Source:MyServiceImplTest.java
...85 coffee.setId(3L);86 87 Optional<Coffee> coffeeO = Optional.of(coffee);88 89 when(coffeeRepo.findById(ArgumentMatchers.anyLong())).thenReturn(coffeeO);90 91 Coffee returned = service.findCoffeeById(ArgumentMatchers.anyLong());92 93 assertEquals(coffee.getId(), returned.getId());94 95 verify(coffeeRepo, times(1)).findById(ArgumentMatchers.anyLong());96 97 }98 99 @Test100 public void saveCoffeeTestNew() { 101 102 Coffee coffee = new Coffee();103 //coffee.setId(4L);104 coffee.setIngredients(Arrays.asList(new Ingredient(), new Ingredient()));105 106 //Optional<Coffee> c1 = Optional.of(coffee); 107 108 when(coffeeRepo.findById(ArgumentMatchers.anyLong())).thenReturn(null);109 when(coffeeRepo.save(ArgumentMatchers.any(Coffee.class))).thenReturn(coffee);110 111 Coffee saved = service.saveCoffee(coffee);112 113 List<Ingredient> list = saved.getIngredients();114 115 assertNull(saved.getId());116 assertEquals(2, list.size());117 assertNull(saved.getNote());118 119 }120 121 @Test122 public void saveCoffeeTestUpdate() { 123 124 Coffee coffee = new Coffee();125 coffee.setId(4L);126 coffee.setIngredients(Arrays.asList(new Ingredient(), new Ingredient()));127 128 Optional<Coffee> c1 = Optional.of(coffee); 129 130 when(coffeeRepo.findById(ArgumentMatchers.anyLong())).thenReturn(c1);131 when(coffeeRepo.save(ArgumentMatchers.any(Coffee.class))).thenReturn(null);132 133 Coffee saved = service.saveCoffee(coffee);134 135 List<Ingredient> list = saved.getIngredients();136 137 assertEquals(coffee.getId(), saved.getId());138 assertEquals(2, list.size());139 assertNull(saved.getNote());140 141 }142 143 @Test144 public void deleteCoffeeByIdTest() {145 146 service.deleteCoffeeById(ArgumentMatchers.anyLong());147 148 verify(coffeeRepo, only()).deleteById(ArgumentMatchers.anyLong());149 150 }151 152 @Test153 public void findIngredientsByIdTest() throws IOException {154 155 Coffee cf = new Coffee();156 cf.setIngredients(Arrays.asList(new Ingredient(), new Ingredient()));157 158 Optional<Coffee> optional = Optional.of(cf);159 160 when(coffeeRepo.findById(ArgumentMatchers.anyLong())).thenReturn(optional);161 162 List<Ingredient> list = service.findIngredientsById(1L);163 164 verify(coffeeRepo, only()).findById(ArgumentMatchers.anyLong()); 165 166 assertEquals(2, list.size());167 }168 169 170}
...
Source:PolicyConverterTest.java
...4package org.chromium.policy;5import static org.mockito.ArgumentMatchers.any;6import static org.mockito.ArgumentMatchers.anyBoolean;7import static org.mockito.ArgumentMatchers.anyInt;8import static org.mockito.ArgumentMatchers.anyLong;9import static org.mockito.ArgumentMatchers.anyString;10import static org.mockito.Mockito.doNothing;11import static org.mockito.Mockito.spy;12import static org.mockito.Mockito.verify;13import android.os.Build;14import android.os.Bundle;15import org.junit.Test;16import org.junit.runner.RunWith;17import org.robolectric.annotation.Config;18import org.chromium.base.test.BaseRobolectricTestRunner;19/**20 * Robolectric test for AbstractAppRestrictionsProvider.21 */22@RunWith(BaseRobolectricTestRunner.class)23@Config(manifest = Config.NONE, sdk = Build.VERSION_CODES.LOLLIPOP)24public class PolicyConverterTest {25 /**26 * Test method for27 * {@link org.chromium.policy.PolicyConverter#setPolicy(java.lang.String, java.lang.Object)}.28 */29 @Test30 public void testSetPolicy() {31 // Stub out the native methods.32 PolicyConverter policyConverter = spy(PolicyConverter.create(1234));33 doNothing()34 .when(policyConverter)35 .nativeSetPolicyBoolean(anyLong(), anyString(), anyBoolean());36 doNothing().when(policyConverter).nativeSetPolicyInteger(anyLong(), anyString(), anyInt());37 doNothing()38 .when(policyConverter)39 .nativeSetPolicyString(anyLong(), anyString(), anyString());40 doNothing()41 .when(policyConverter)42 .nativeSetPolicyStringArray(anyLong(), anyString(), any(String[].class));43 policyConverter.setPolicy("p1", true);44 verify(policyConverter).nativeSetPolicyBoolean(1234, "p1", true);45 policyConverter.setPolicy("p1", 5678);46 verify(policyConverter).nativeSetPolicyInteger(1234, "p1", 5678);47 policyConverter.setPolicy("p1", "hello");48 verify(policyConverter).nativeSetPolicyString(1234, "p1", "hello");49 policyConverter.setPolicy("p1", new String[] {"hello", "goodbye"});50 verify(policyConverter)51 .nativeSetPolicyStringArray(1234, "p1", new String[] {"hello", "goodbye"});52 Bundle b1 = new Bundle();53 b1.putInt("i1", 23);54 b1.putString("s1", "a string");55 Bundle[] ba = new Bundle[1];56 ba[0] = new Bundle();...
anyLong
Using AI Code Generation
1import org.junit.Test;2import org.junit.runner.RunWith;3import org.mockito.InjectMocks;4import org.mockito.Mock;5import org.mockito.junit.MockitoJUnitRunner;6import java.util.List;7import static org.mockito.ArgumentMatchers.anyLong;8import static org.mockito.Mockito.verify;9@RunWith(MockitoJUnitRunner.class)10public class MockTest {11 List<String> mockList;12 MockTest mockTest;13 public void testMock() {14 mockTest.mockList.add("Test");15 verify(mockList).add(anyLong());16 }17}18 -> at MockTest.testMock(MockTest.java:21)19 verify(mock).doStuff(anyInt());20 when(mock.get(anyObject())).thenReturn("foo");21 doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());22 ArgumentMatchers.anyInt()23 ArgumentMatchers.anyObject()24 ArgumentMatchers.anyString()25at org.mockito.internal.verification.api.VerificationDataImpl.<init>(VerificationDataImpl.java:51)26at org.mockito.internal.verification.AtLeast.<init>(AtLeast.java:23)27at org.mockito.internal.verification.VerificationModeFactory.atLeast(VerificationModeFactory.java:27)28at org.mockito.internal.verification.VerificationModeFactory.atLeast(VerificationModeFactory.java:20)29at org.mockito.internal.verification.api.VerificationDataFactory.create(VerificationDataFactory.java:33)30at org.mockito.internal.verification.api.VerificationDataFactory.create(VerificationDataFactory.java:24)31at org.mockito.internal.verification.VerificationOverTimeImpl.verify(VerificationOverTimeImpl.java:53)32at org.mockito.internal.verification.VerificationOverTimeImpl.verify(VerificationOverTimeImpl.java:43)33at org.mockito.internal.verification.api.VerificationOverTime.verify(VerificationOverTime.java:27)34at org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:56)35at org.junit.rules.RunRules.evaluate(RunRules.java:20)36at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
anyLong
Using AI Code Generation
1package com.automationtesting;2import static org.mockito.ArgumentMatchers.anyLong;3import static org.mockito.Mockito.mock;4import static org.mockito.Mockito.when;5import java.util.List;6import org.junit.Test;7public class MockitoAnyLongMethod {8 public void test() {9 List mockList = mock(List.class);10 when(mockList.get(anyLong())).thenReturn("Mockito");11 System.out.println(mockList.get(1));12 }13}14Related Posts: Mockito anyInt() Method15Mockito anyString() Method16Mockito any() Method17Mockito anyBoolean() Method18Mockito anyDouble() Method19Mockito anyFloat() Method20Mockito anyList() Method21Mockito anyMap() Method22Mockito anySet() Method23Mockito anyVararg() Method
anyLong
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anyLong;2import static org.mockito.Mockito.when;3import static org.mockito.Mockito.mock;4import static org.mockito.Mockito.verify;5import static org.mockito.Mockito.times;6import static org.mockito.Mockito.anyInt;7import static org.mockito.Mockito.anyString;8import static org.mockito.Mockito.any;9import static org.mockito.Mockito.doNothing;10import static org.mockito.Mockito.doThrow;11import static org.mockito.Mockito.doReturn;12import static org.mockito.Mockito.spy;13import static org.mockito.Mockito.verifyNoMoreInteractions;14import static org.mockito.Mockito.verifyZeroInteractions;15import static org.mockito.Mockito.never;16import static org.mockito.Mockito.atLeast;17import static org.mockito.Mockito.atLeastOnce;18import static org.mockito.Mockito.atMost;19import static org.mockito.Mockito.only;20import static org.mockito.Mockito.inOrder;21import static org.mockito.Mockito.timeout;22import static org.mockito.Mockito.verifyNoInteractions;23import static org.mockito.Mockito.reset;24import static org.mockito.Mockito.withSettings;25import static org.mockito.Mockito.RETURNS_SMART_NULLS;26import static org.mockito.Mockito.RETURNS_DEEP_STUBS;27import static org.mockito.Mockito.RETURNS_DEFAULTS;28import static org.mockito.Mockito.RETURNS_MOCKS;29import static org.mockito.Mockito.RETURNS_SELF;30import static org.mockito.Mockito.RETURNS_
anyLong
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import static org.mockito.Mockito.*;3public class anyLongExample {4 public static void main(String[] args) {5 Foo foo = mock(Foo.class);6 when(foo.doSomething(ArgumentMatchers.anyLong())).thenReturn("Hello World!");7 System.out.println(foo.doSomething(1));8 System.out.println(foo.doSomething(2));9 System.out.println(foo.doSomething(3));10 }11}12Example 2: Using anyLong() method of ArgumentMatchers class13import org.mockito.ArgumentMatchers;14import static org.mockito.Mockito.*;15public class anyLongExample {16 public static void main(String[] args) {17 Foo foo = mock(Foo.class);18 when(foo.doSomething(ArgumentMatchers.anyLong())).thenReturn("Hello World!");19 System.out.println(foo.doSomething(1));20 System.out.println(foo.doSomething(2));21 System.out.println(foo.doSomething(3));22 }23}24Example 3: Using anyLong() method of ArgumentMatchers class25import org.mockito.ArgumentMatchers;26import static org.mockito.Mockito.*;27public class anyLongExample {28 public static void main(String[] args) {29 Foo foo = mock(Foo.class);30 when(foo.doSomething(ArgumentMatchers.anyLong())).thenReturn("Hello World!");31 System.out.println(foo.doSomething(1));32 System.out.println(foo.doSomething(2));33 System.out.println(foo.doSomething(3));34 }35}36Example 4: Using anyLong() method of ArgumentMatchers class37import org.mockito.ArgumentMatchers;38import static org.mockito.Mockito.*;39public class anyLongExample {40 public static void main(String[] args) {41 Foo foo = mock(Foo.class);42 when(foo.doSomething(ArgumentMatchers.anyLong())).thenReturn("Hello World!");43 System.out.println(foo.doSomething(1));44 System.out.println(foo.doSomething(2));45 System.out.println(foo.doSomething(3));46 }47}
anyLong
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anyLong;2import java.util.ArrayList;3import java.util.List;4import org.junit.Test;5import org.mockito.Mockito;6public class MockitoTest {7 public void test() {8 List list = Mockito.mock(ArrayList.class);9 Mockito.when(list.get(anyLong())).thenReturn("Hello");10 System.out.println(list.get(10));11 }12}
anyLong
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anyLong;2import static org.mockito.Mockito.*;3import org.mockito.Mockito;4import org.mockito.invocation.InvocationOnMock;5import org.mockito.stubbing.Answer;6import java.util.*;7import java.util.function.Function;8import java.util.stream.Collectors;9import java.util.stream.Stream;10import java.util.function.Supplier;11import java.util.function.Predicate;12import java.util.function.Consumer;13import java.util.function.BiConsumer;14import java.util.function.BiFunction;15import java.util.function.BinaryOperator;16import java.util.function.UnaryOperator;17import java.util.function.BiPredicate;18import java.util.function.IntConsumer;19import java.util.function.IntFunction;20import java.util.function.IntPredicate;21import java.util.function.IntSupplier;22import java.util.function.IntToDoubleFunction;23import java.util.function.IntToLongFunction;24import java.util.function.IntUnaryOperator;25import java.util.function.LongConsumer;26import java.util.function.LongFunction;27import java.util.function.LongPredicate;28import java.util.function.LongSupplier;29import java.util.function.LongToDoubleFunction;30import java.util.function.LongToIntFunction;31import java.util.function.LongUnaryOperator;32import java.util.function.DoubleConsumer;33import java.util.function.DoubleFunction;34import java.util.function.DoublePredicate;35import java.util.function.DoubleSupplier;36import java.util.function.DoubleToIntFunction;37import java.util.function.DoubleToLongFunction;38import java.util.function.DoubleUnaryOperator;39import java.util.function.ObjIntConsumer;40import java.util.function.ObjLongConsumer;41import java.util.function.ObjDoubleConsumer;42import java.util.function.Function;43import java.util.function.BiFunction;44import java.util.function.Supplier;45import java.util.function.Consumer;46import java.util.function.BiConsumer;47import java.util.function.Predicate;48import java.util.function.BiPredicate;49import java.util.function.UnaryOperator;50import java.util.function.BinaryOperator;51import java.util.function.IntFunction;52import java.util.function.IntToLongFunction;53import java.util.function.IntToDoubleFunction;54import java.util.function.IntUnaryOperator;55import java.util.function.IntBinaryOperator;56import java.util.function.LongFunction;57import java.util.function.LongToIntFunction;58import java.util.function.LongToDoubleFunction;59import java.util.function.LongUnaryOperator;60import java.util.function.LongBinaryOperator;61import java.util.function.DoubleFunction;62import java.util.function.DoubleToIntFunction;63import java.util.function.DoubleToLongFunction;64import java.util.function.DoubleUnaryOperator;65import java.util.function.DoubleBinaryOperator;66import java.util.function.IntConsumer;67import java.util.function
anyLong
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3import org.mockito.MockitoAnnotations;4import org.mockito.Mock;5import org.mockito.InjectMocks;6import org.mockito.junit.MockitoJUnitRunner;7import org.junit.runner.RunWith;8import org.junit.Before;9import org.junit.Test;10import static org.mockito.Mockito.when;11import static org.mockito.Mockito.anyLong;12import static org.mockito.Mockito.any;13import static org.mockito.Mockito.doNothing;14import static org.mockito.Mockito.times;15import static org.mockito.Mockito.verify;16import static org.mockito.Mockito.verifyNoMoreInteractions;17import static org.mockito.Mockito.verifyZeroInteractions;18import static org.mockito.Mockito.spy;19import static org.mockito.Mockito.doReturn;20import static org.mockito.Mockito.doThrow;21import static org.mockito
anyLong
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3import static org.mockito.Mockito.mock;4import static org.mockito.Mockito.when;5import static org.mockito.Mockito.anyLong;6import static org.mockito.Mockito.any;7public class MockitoAnyLong {8 public static void main(String[] args) {9 MyInterface myInterface = mock(MyInterface.class);10 when(myInterface.anyLongMethod(anyLong())).thenReturn("anyLong");11 System.out.println(myInterface.anyLongMethod(10));12 }13}14interface MyInterface {15 String anyLongMethod(long l);16}17Example 2: Using anyLong() method with a long parameter18import org.mockito.ArgumentMatchers;19import org.mockito.Mockito;20import static org.mockito.Mockito.mock;21import static org.mockito.Mockito.when;22import static org.mockito.Mockito.anyLong;23import static org.mockito.Mockito.any;24public class MockitoAnyLong {25 public static void main(String[] args) {26 MyInterface myInterface = mock(MyInterface.class);27 when(myInterface.anyLongMethod(anyLong())).thenReturn("anyLong");28 System.out.println(myInterface.anyLongMethod(10));29 }30}31interface MyInterface {32 String anyLongMethod(long l);33}34Example 3: Using anyLong() method with a primitive long parameter35import org.mockito.ArgumentMatchers;36import org.mockito.Mockito;37import static org.mockito.Mockito.mock;38import static org.mockito.Mockito.when;39import static org.mockito.Mockito.anyLong;40import static org.mockito.Mockito.any;41public class MockitoAnyLong {42 public static void main(String[] args) {43 MyInterface myInterface = mock(MyInterface.class);44 when(myInterface.anyLongMethod(anyLong())).thenReturn("anyLong");45 System.out.println(myInterface.anyLongMethod(10));46 }47}48interface MyInterface {49 String anyLongMethod(long l);50}51Example 4: Using anyLong() method with
anyLong
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anyLong;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.when;4public class MockitoExample {5 public static void main(String[] args) {6 MyDatabase databaseMock = mock(MyDatabase.class);7 when(databaseMock.isAvailable(anyLong())).thenReturn(true);8 boolean check = databaseMock.isAvailable(1234L);9 System.out.println(check);10 }11}12import static org.mockito.ArgumentMatchers.anyString;13import static org.mockito.Mockito.mock;14import static org.mockito.Mockito.when;15public class MockitoExample {16 public static void main(String[] args) {17 MyDatabase databaseMock = mock(MyDatabase.class);18 when(databaseMock.isAvailable(anyString())).thenReturn(true);19 boolean check = databaseMock.isAvailable("1234");20 System.out.println(check);21 }22}23import static org.mockito.ArgumentMatchers.anyInt;24import static org.mockito.Mockito.mock;25import static org.mockito.Mockito.when;26public class MockitoExample {27 public static void main(String[] args) {28 MyDatabase databaseMock = mock(MyDatabase.class);29 when(databaseMock.isAvailable(anyInt())).thenReturn(true);30 boolean check = databaseMock.isAvailable(1234);31 System.out.println(check);32 }33}34import static org.mockito.ArgumentMatchers.any;35import static org.mockito.Mockito.mock;36import static org.mockito.Mockito.when;37public class MockitoExample {38 public static void main(String[] args) {39 MyDatabase databaseMock = mock(MyDatabase.class);40 when(databaseMock.isAvailable(any())).thenReturn(true);41 boolean check = databaseMock.isAvailable("1234");42 System.out.println(check);43 }44}
anyLong
Using AI Code Generation
1public class Test {2 public static void main(String[] args) {3 List mockedList = mock(List.class);4 when(mockedList.get(anyLong())).thenReturn("element");5 System.out.println(mockedList.get(9999999));6 verify(mockedList).get(anyLong());7 }8}9import org.mockito.ArgumentMatchers;10import static org.mockito.ArgumentMatchers.anyObject;11public class Test {12 public static void main(String[] args) {13 List mockedList = mock(List.class);14 when(mockedList.get(anyObject())).thenReturn("element");15 System.out.println(mockedList.get(9999999));16 verify(mockedList).get(anyObject());17 }18}19import org.mockito.ArgumentMatchers;20import static org.mockito.ArgumentMatchers.anyString;21public class Test {22 public static void main(String[] args) {23 List mockedList = mock(List.class);24 when(mockedList.get(anyString())).thenReturn("element");25 System.out.println(mockedList.get("9999999"));26 verify(mockedList).get(anyString());27 }28}29import org.mockito.ArgumentMatchers;30import static org.mockito.ArgumentMatchers.list;31public class Test {32 public static void main(String[] args) {33 List mockedList = mock(List.class);34 when(mockedList.get(list(1,2,35import static org.mockito.ArgumentMatchers.anyInt;36import static org.mockito.Mockito.mock;37import static org.mockito.Mockito.when;38public class MockitoExample {39 public static void main(String[] args) {40 MyDatabase databaseMock = mock(MyDatabase.class);41 when(databaseMock.isAvailable(anyInt())).thenReturn(true);42 boolean check = databaseMock.isAvailable(1234);43 System.out.println(check);44 }45}46import static org.mockito.ArgumentMatchers.any;47import static org.mockito.Mockito.mock;48import static org.mockito.Mockito.when;49public class MockitoExample {50 public static void main(String[] args) {51 MyDatabase databaseMock = mock(MyDatabase.class);52 when(databaseMock.isAvailable(any())).thenReturn(true);53 boolean check = databaseMock.isAvailable("1234");54 System.out.println(check);55 }56}
anyLong
Using AI Code Generation
1public class Test {2 public static void main(String[] args) {3 List mockedList = mock(List.class);4 when(mockedList.get(anyLong())).thenReturn("element");5 System.out.println(mockedList.get(9999999));6 verify(mockedList).get(anyLong());7 }8}9import org.mockito.ArgumentMatchers;10import static org.mockito.ArgumentMatchers.anyObject;11public class Test {12 public static void main(String[] args) {13 List mockedList = mock(List.class);14 when(mockedList.get(anyObject())).thenReturn("element");15 System.out.println(mockedList.get(9999999));16 verify(mockedList).get(anyObject());17 }18}19import org.mockito.ArgumentMatchers;20import static org.mockito.ArgumentMatchers.anyString;21public class Test {22 public static void main(String[] args) {23 List mockedList = mock(List.class);24 when(mockedList.get(anyString())).thenReturn("element");25 System.out.println(mockedList.get("9999999"));26 verify(mockedList).get(anyString());27 }28}29import org.mockito.ArgumentMatchers;30import static org.mockito.ArgumentMatchers.list;31public class Test {32 public static void main(String[] args) {33 List mockedList = mock(List.class);34 when(mockedList.get(list(1,2,
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!!