Best Mockito code snippet using org.mockito.ArgumentMatchers.anyCollection
Source:UserEndpointTest.java
...97 user.addTags(invocation.getArgument(0));98 return Mono.just(user);99 })100 .when(userService)101 .addUserTags(ArgumentMatchers.anyCollection(), ArgumentMatchers.eq(user));102 Object result = mockMvc.perform(MockMvcRequestBuilders103 .put("/user/{login}/tags", LOGIN)104 .accept(MediaType.APPLICATION_JSON_UTF8)105 .contentType(MediaType.APPLICATION_JSON_UTF8)106 .param("tags", TAGS)107 )108 .andDo(MockMvcResultHandlers.print())109 .andExpect(status().isOk())110 .andReturn()111 .getAsyncResult();112 assertTrue(result instanceof User);113 User resUser = (User) result;114 assertEquals(resUser.getTags(), new HashSet<>(Arrays.asList(TAGS)));115 }116 @Test117 public void deleteUserTagsShouldReturnOkData() throws Exception{118 user.addTags(Arrays.asList(TAGS));119 assertEquals(user.getTags(), new HashSet<>(Arrays.asList(TAGS)));120 Mockito.doAnswer(invocation -> {121 user.deleteTags(invocation.getArgument(0));122 return Mono.just(user);123 })124 .when(userService)125 .deleteUserTags(ArgumentMatchers.anyCollection(), ArgumentMatchers.eq(user));126 Object result = mockMvc.perform(MockMvcRequestBuilders127 .delete("/user/{login}/tags", LOGIN)128 .accept(MediaType.APPLICATION_JSON_UTF8)129 .contentType(MediaType.APPLICATION_JSON_UTF8)130 .param("tags", TAGS)131 )132 .andDo(MockMvcResultHandlers.print())133 .andExpect(status().isOk())134 .andReturn()135 .getAsyncResult();136 assertTrue(result instanceof User);137 User resUser = (User) result;138 assertEquals(resUser.getTags().size(),0);139 }140 @Test141 public void addUserClientsShouldReturnOkData() throws Exception{142 Mockito.doAnswer(invocation -> {143 user.addClients(invocation.getArgument(0));144 return Mono.just(user);145 })146 .when(userService)147 .addUserClients(ArgumentMatchers.anyCollection(), ArgumentMatchers.eq(user));148 Object result = mockMvc.perform(MockMvcRequestBuilders149 .put("/user/{login}/clients", LOGIN)150 .accept(MediaType.APPLICATION_JSON_UTF8)151 .contentType(MediaType.APPLICATION_JSON_UTF8)152 .param("clients", CLIENTS)153 )154 .andDo(MockMvcResultHandlers.print())155 .andExpect(status().isOk())156 .andReturn()157 .getAsyncResult();158 assertTrue(result instanceof User);159 User resUser = (User) result;160 assertEquals(resUser.getClients(), new HashSet<>(Arrays.asList(CLIENTS)));161 }162 @Test163 public void deleteUserClients() throws Exception {164 user.addClients(Arrays.asList(CLIENTS));165 assertEquals(user.getClients(), new HashSet<>(Arrays.asList(CLIENTS)));166 Mockito.doAnswer(invocation -> {167 user.deleteClients(invocation.getArgument(0));168 return Mono.just(user);169 })170 .when(userService)171 .deleteUserClients(ArgumentMatchers.anyCollection(), ArgumentMatchers.eq(user));172 Object result = mockMvc.perform(MockMvcRequestBuilders173 .delete("/user/{login}/clients", LOGIN)174 .accept(MediaType.APPLICATION_JSON_UTF8)175 .contentType(MediaType.APPLICATION_JSON_UTF8)176 .param("clients", CLIENTS)177 )178 .andDo(MockMvcResultHandlers.print())179 .andExpect(status().isOk())180 .andReturn()181 .getAsyncResult();182 assertTrue(result instanceof User);183 User resUser = (User) result;184 assertEquals(resUser.getClients().size(),0);185 }186 /*187 @Test188 public void updateUserInfo() throws Exception{189 }190*/191 @Test192 public void addUserGroups() throws Exception{193 Mockito.doAnswer(invocation -> {194 user.addGroups(invocation.getArgument(0));195 return Mono.just(user);196 })197 .when(userService)198 .addUserGroups(ArgumentMatchers.anyCollection(), ArgumentMatchers.eq(user));199 mockUserServiceAddCollection(strings -> userService.addUserGroups(strings, user), user);200 Object result = mockMvc.perform(MockMvcRequestBuilders201 .put("/user/{login}/groups", LOGIN)202 .accept(MediaType.APPLICATION_JSON_UTF8)203 .contentType(MediaType.APPLICATION_JSON_UTF8)204 .param("groups", GROUPS)205 )206 .andDo(MockMvcResultHandlers.print())207 .andExpect(status().isOk())208 .andReturn()209 .getAsyncResult();210 assertTrue(result instanceof User);211 User resUser = (User) result;212 assertEquals(resUser.getClients(), new HashSet<>(Arrays.asList(CLIENTS)));213 }214 @Test215 public void deleteUserGroups()throws Exception {216 }217 private void mockUserServiceAddCollection(Consumer<Collection<String>> userServiceMethod, User user){218 Mockito.doAnswer(invocation -> {219 // userServiceMethod.accept(invocation.getArgument(0));220 return Mono.just(user);221 })222 .when(userService)223 .addUserGroups(ArgumentMatchers.anyCollection(), ArgumentMatchers.eq(user));224 }225/*226 private void checkAddCollection(Consumer<Collection<String>> userServiceMethod){227 Object result = mockMvc.perform(MockMvcRequestBuilders228 .put("/user/{login}/groups", LOGIN)229 .accept(MediaType.APPLICATION_JSON_UTF8)230 .contentType(MediaType.APPLICATION_JSON_UTF8)231 .param("groups", GROUPS)232 )233 .andDo(MockMvcResultHandlers.print())234 .andExpect(status().isOk())235 .andReturn()236 .getAsyncResult();237 assertTrue(result instanceof User);...
Source:LiveIssueCacheTest.java
...28import org.junit.rules.ExpectedException;29import org.sonarlint.intellij.issue.LiveIssue;30import org.sonarlint.intellij.util.SonarLintAppUtils;31import static org.assertj.core.api.Assertions.assertThat;32import static org.mockito.ArgumentMatchers.anyCollection;33import static org.mockito.ArgumentMatchers.anyString;34import static org.mockito.ArgumentMatchers.eq;35import static org.mockito.Mockito.doThrow;36import static org.mockito.Mockito.mock;37import static org.mockito.Mockito.verify;38import static org.mockito.Mockito.verifyNoMoreInteractions;39import static org.mockito.Mockito.verifyZeroInteractions;40import static org.mockito.Mockito.when;41public class LiveIssueCacheTest {42 private IssuePersistence store = mock(IssuePersistence.class);43 private SonarLintAppUtils appUtils = mock(SonarLintAppUtils.class);44 private Project project = mock(Project.class);45 @Rule46 public ExpectedException exception = ExpectedException.none();47 private LiveIssueCache cache = new LiveIssueCache(project, store, appUtils, 10);48 @Before49 public void setUp() {50 when(project.getBasePath()).thenReturn("/root");51 }52 @Test53 public void should_save_and_read_cache_only() {54 VirtualFile file = createTestFile("file1");55 LiveIssue issue1 = createTestIssue("will be overwritten");56 LiveIssue issue2 = createTestIssue("r1");57 cache.save(file, Collections.singleton(issue1));58 cache.save(file, Collections.singleton(issue2));59 assertThat(cache.contains(file)).isTrue();60 assertThat(cache.getLive(file)).containsOnly(issue2);61 assertThat(cache.contains(createTestFile("file2"))).isFalse();62 verifyZeroInteractions(store);63 }64 @Test65 public void should_return_contains_even_if_empty() {66 VirtualFile file = createTestFile("file1");67 cache.save(file, Collections.emptyList());68 assertThat(cache.contains(file)).isTrue();69 assertThat(cache.getLive(file)).isEmpty();70 }71 @Test72 public void should_not_fallback_persistence() {73 VirtualFile file = createTestFile("file1");74 LiveIssue issue1 = createTestIssue("r1");75 cache.save(file, Collections.singleton(issue1));76 VirtualFile cacheMiss = createTestFile("file2");77 assertThat(cache.getLive(cacheMiss)).isNull();78 verifyZeroInteractions(store);79 }80 @Test81 public void should_flush_if_full() throws IOException {82 LiveIssue issue1 = createTestIssue("r1");83 VirtualFile file0 = createTestFile("file0");84 cache.save(file0, Collections.singleton(issue1));85 for (int i = 1; i < 10; i++) {86 VirtualFile file = createTestFile("file" + i);87 cache.save(file, Collections.singleton(issue1));88 }89 // oldest access should be file1 after this90 assertThat(cache.getLive(file0)).containsOnly(issue1);91 verifyZeroInteractions(store);92 VirtualFile file = createTestFile("anotherfile");93 cache.save(file, Collections.singleton(issue1));94 verify(store).save(eq("file1"), anyCollection());95 }96 @Test97 public void should_clear_store() {98 LiveIssue issue1 = createTestIssue("r1");99 VirtualFile file0 = createTestFile("file0");100 cache.save(file0, Collections.singleton(issue1));101 cache.clear();102 verify(store).clear();103 assertThat(cache.getLive(file0)).isNull();104 }105 @Test106 public void should_flush_when_requested() throws IOException {107 LiveIssue issue1 = createTestIssue("r1");108 VirtualFile file0 = createTestFile("file0");109 cache.save(file0, Collections.singleton(issue1));110 VirtualFile file1 = createTestFile("file1");111 cache.save(file1, Collections.singleton(issue1));112 cache.flushAll();113 verify(store).save(eq("file0"), anyCollection());114 verify(store).save(eq("file1"), anyCollection());115 verifyNoMoreInteractions(store);116 }117 @Test118 public void error_flush() throws IOException {119 doThrow(new IOException()).when(store).save(anyString(), anyCollection());120 LiveIssue issue1 = createTestIssue("r1");121 VirtualFile file0 = createTestFile("file0");122 cache.save(file0, Collections.singleton(issue1));123 exception.expect(IllegalStateException.class);124 cache.flushAll();125 }126 @Test127 public void error_remove_eldest() throws IOException {128 doThrow(new IOException()).when(store).save(anyString(), anyCollection());129 LiveIssue issue1 = createTestIssue("r1");130 for (int i = 0; i < 10; i++) {131 VirtualFile file = createTestFile("file" + i);132 cache.save(file, Collections.singleton(issue1));133 }134 exception.expect(IllegalStateException.class);135 cache.save(createTestFile("anotherfile"), Collections.singleton(issue1));136 }137 @Test138 public void should_flush_on_project_closed() throws IOException {139 LiveIssue issue1 = createTestIssue("r1");140 VirtualFile file0 = createTestFile("file0");141 cache.save(file0, Collections.singleton(issue1));142 VirtualFile file1 = createTestFile("file1");143 cache.save(file1, Collections.singleton(issue1));144 cache.projectClosed();145 verify(store).save(eq("file0"), anyCollection());146 verify(store).save(eq("file1"), anyCollection());147 verifyNoMoreInteractions(store);148 }149 private LiveIssue createTestIssue(String ruleKey) {150 LiveIssue issue = mock(LiveIssue.class);151 when(issue.getRuleKey()).thenReturn(ruleKey);152 when(issue.getAssignee()).thenReturn("assignee");153 when(issue.getRuleName()).thenReturn(ruleKey);154 when(issue.getSeverity()).thenReturn("MAJOR");155 when(issue.getMessage()).thenReturn("msg");156 return issue;157 }158 private VirtualFile createTestFile(String path) {159 VirtualFile file = mock(VirtualFile.class);160 when(file.isValid()).thenReturn(true);...
Source:DefensiveFirstStrikeTest.java
...5import static org.hamcrest.Matchers.is;6import static org.hamcrest.collection.IsEmptyCollection.empty;7import static org.mockito.ArgumentMatchers.any;8import static org.mockito.ArgumentMatchers.anyBoolean;9import static org.mockito.ArgumentMatchers.anyCollection;10import static org.mockito.ArgumentMatchers.anyString;11import static org.mockito.Mockito.never;12import static org.mockito.Mockito.verify;13import games.strategy.engine.delegate.IDelegateBridge;14import games.strategy.triplea.delegate.ExecutionStack;15import games.strategy.triplea.delegate.battle.BattleActions;16import games.strategy.triplea.delegate.battle.BattleState;17import games.strategy.triplea.delegate.battle.steps.BattleStep;18import games.strategy.triplea.delegate.battle.steps.BattleStep.Order;19import games.strategy.triplea.delegate.battle.steps.fire.firststrike.BattleStateBuilder.BattleStateVariation;20import java.util.List;21import org.junit.jupiter.api.Test;22import org.junit.jupiter.api.extension.ExtendWith;23import org.junit.jupiter.params.ParameterizedTest;24import org.junit.jupiter.params.provider.Arguments;25import org.junit.jupiter.params.provider.MethodSource;26import org.mockito.Mock;27import org.mockito.junit.jupiter.MockitoExtension;28@ExtendWith(MockitoExtension.class)29class DefensiveFirstStrikeTest {30 @Mock ExecutionStack executionStack;31 @Mock IDelegateBridge delegateBridge;32 @Mock BattleActions battleActions;33 @Test34 void willNotExecuteIfNoDefensiveFirstStrikeAvailable() {35 final BattleState battleState =36 givenBattleState(List.of(BattleStateVariation.HAS_ATTACKING_FIRST_STRIKE));37 final DefensiveFirstStrike defensiveFirstStrike =38 new DefensiveFirstStrike(battleState, battleActions);39 assertThat(defensiveFirstStrike.getNames(), is(empty()));40 defensiveFirstStrike.execute(executionStack, delegateBridge);41 verify(battleActions, never())42 .findTargetGroupsAndFire(43 any(),44 anyString(),45 anyBoolean(),46 any(),47 any(),48 anyCollection(),49 anyCollection(),50 anyCollection(),51 anyCollection());52 }53 @ParameterizedTest54 @MethodSource55 void getStep(final List<BattleStateVariation> parameters, final BattleStep.Order stepOrder) {56 final BattleState battleState = givenBattleState(parameters);57 final DefensiveFirstStrike defensiveFirstStrike =58 new DefensiveFirstStrike(battleState, battleActions);59 assertThat(defensiveFirstStrike.getNames(), hasSize(2));60 assertThat(defensiveFirstStrike.getOrder(), is(stepOrder));61 defensiveFirstStrike.execute(executionStack, delegateBridge);62 verify(battleActions)63 .findTargetGroupsAndFire(64 any(),65 anyString(),66 anyBoolean(),67 any(),68 any(),69 anyCollection(),70 anyCollection(),71 anyCollection(),72 anyCollection());73 }74 static List<Arguments> getStep() {75 return List.of(76 Arguments.of(77 List.of(BattleStateVariation.HAS_DEFENDING_FIRST_STRIKE),78 Order.FIRST_STRIKE_DEFENSIVE_REGULAR),79 Arguments.of(80 List.of(81 BattleStateVariation.HAS_DEFENDING_FIRST_STRIKE,82 BattleStateVariation.HAS_ATTACKING_DESTROYER),83 Order.FIRST_STRIKE_DEFENSIVE_REGULAR),84 Arguments.of(85 List.of(86 BattleStateVariation.HAS_DEFENDING_FIRST_STRIKE, BattleStateVariation.HAS_WW2V2),...
Source:ProjectServiceTest.java
...20import reactor.core.publisher.Mono;21import reactor.test.StepVerifier;22import java.util.List;23import static org.mockito.ArgumentMatchers.any;24import static org.mockito.ArgumentMatchers.anyCollection;25import static org.mockito.ArgumentMatchers.anyIterable;26import static org.mockito.ArgumentMatchers.anyLong;27import static org.mockito.ArgumentMatchers.anyString;28import static org.mockito.Mockito.when;29/**30 * @author Anton Lamtev31 */32@WebFluxTest33@ContextConfiguration(classes = {34 ProjectService.class,35})36class ProjectServiceTest {37 @Autowired38 ProjectService projectService;39 @MockBean40 ProjectRepo projectRepo;41 @MockBean42 GithubUserRepo githubUserRepo;43 @MockBean44 GithubRepoRepo githubRepoRepo;45 @MockBean46 SnapshotRepo snapshotRepo;47 @MockBean48 PullRepo pullRepo;49 @MockBean50 CodeLoader codeLoader;51 @MockBean52 CloneDetectionService cloneDetectionService;53 @MockBean54 CurrentUserRepo currentUserRepo;55 @Test56 void testInitSinglePull() {57 final var pull = GithubApiToModelConverter.convert(GithubWebhookRouterTest.pullOpenedPayload.pull());58 final var snap = pull.head();59 when(githubUserRepo.upsert(anyCollection()))60 .thenReturn(Flux.empty());61 when(githubRepoRepo.upsert(anyCollection()))62 .thenReturn(Flux.empty());63 when(codeLoader.loadCommits(any(), anyString()))64 .thenReturn(Flux.just(snap.commit()));65 when(snapshotRepo.insert(anyIterable()))66 .thenReturn(Flux.empty());67 when(pullRepo.upsert(any(Pull.class)))68 .thenReturn(Mono.empty());69 when(pullRepo.mapSnapshots(any(PullSnapshots.class)))70 .thenReturn(Mono.empty());71 StepVerifier.create(projectService.init(GithubWebhookRouterTest.pullOpenedPayload.pull()))72 .expectNext(PullSnapshots.of(pull, List.of(snap)))73 .verifyComplete();74 }75 @Test76 void testUpdateWithNewPulls() {77 final var pull = GithubApiToModelConverter.convert(GithubWebhookRouterTest.pullSynchronizePayload.pull());78 when(githubUserRepo.upsert(anyCollection()))79 .thenReturn(Flux.empty());80 when(githubRepoRepo.upsert(anyCollection()))81 .thenReturn(Flux.empty());82 when(pullRepo.findById(anyLong()))83 .thenReturn(Mono.just(pull));84 when(codeLoader.loadCommit(any(), anyString()))85 .thenReturn(Mono.just(pull.base().commit()));86 when(codeLoader.loadCommits(any(), anyString(), anyString()))87 .thenReturn(Flux.just(pull.head().commit(), pull.base().commit()));88 when(snapshotRepo.insert(anyIterable()))89 .thenReturn(Flux.empty());90 when(pullRepo.upsert(any(Pull.class)))91 .thenReturn(Mono.empty());92 when(pullRepo.mapSnapshots(any(PullSnapshots.class)))93 .thenReturn(Mono.empty());94 StepVerifier.create(projectService.updateWithNewCommits(GithubWebhookRouterTest.pullSynchronizePayload.pull()))95 .expectNext(PullSnapshots.of(pull, List.of(pull.head(), pull.head().withCommit(pull.base().commit()))))96 .verifyComplete();97 }98 @Test99 void testUpdatePullInfo() {100 final var pull = GithubApiToModelConverter.convert(GithubWebhookRouterTest.assignedPayload.pull());101 when(githubUserRepo.upsert(anyCollection()))102 .thenReturn(Flux.empty());103 when(githubRepoRepo.upsert(anyCollection()))104 .thenReturn(Flux.empty());105 when(pullRepo.upsert(pull))106 .thenReturn(Mono.just(pull));107 StepVerifier.create(projectService.updatePullInfo(GithubWebhookRouterTest.assignedPayload.pull()))108 .expectNext(pull)109 .verifyComplete();110 }111 @Test112 void testHeadFiles() {113 when(codeLoader.loadFilenames(any()))114 .thenReturn(Flux.just("f2", "f1"));115 StepVerifier.create(projectService.headFiles(any()))116 .expectNext(List.of(Project.Conf.KEEP_EXCLUDED_FILES_SYNCED, "f1", "f2"))117 .verifyComplete();...
Source:OffensiveFirstStrikeTest.java
...5import static org.hamcrest.collection.IsEmptyCollection.empty;6import static org.hamcrest.core.Is.is;7import static org.mockito.ArgumentMatchers.any;8import static org.mockito.ArgumentMatchers.anyBoolean;9import static org.mockito.ArgumentMatchers.anyCollection;10import static org.mockito.ArgumentMatchers.anyString;11import static org.mockito.Mockito.never;12import static org.mockito.Mockito.verify;13import games.strategy.engine.delegate.IDelegateBridge;14import games.strategy.triplea.delegate.ExecutionStack;15import games.strategy.triplea.delegate.battle.BattleActions;16import games.strategy.triplea.delegate.battle.BattleState;17import games.strategy.triplea.delegate.battle.steps.BattleStep.Order;18import games.strategy.triplea.delegate.battle.steps.fire.firststrike.BattleStateBuilder.BattleStateVariation;19import java.util.List;20import org.junit.jupiter.api.Test;21import org.junit.jupiter.api.extension.ExtendWith;22import org.junit.jupiter.params.ParameterizedTest;23import org.junit.jupiter.params.provider.Arguments;24import org.junit.jupiter.params.provider.MethodSource;25import org.mockito.Mock;26import org.mockito.junit.jupiter.MockitoExtension;27@ExtendWith(MockitoExtension.class)28class OffensiveFirstStrikeTest {29 @Mock ExecutionStack executionStack;30 @Mock IDelegateBridge delegateBridge;31 @Mock BattleActions battleActions;32 @Test33 void willNotExecuteIfNoOffensiveFirstStrikeAvailable() {34 final BattleState battleState =35 givenBattleState(List.of(BattleStateVariation.HAS_DEFENDING_FIRST_STRIKE));36 final OffensiveFirstStrike offensiveFirstStrike =37 new OffensiveFirstStrike(battleState, battleActions);38 assertThat(offensiveFirstStrike.getNames(), is(empty()));39 offensiveFirstStrike.execute(executionStack, delegateBridge);40 verify(battleActions, never())41 .findTargetGroupsAndFire(42 any(),43 anyString(),44 anyBoolean(),45 any(),46 any(),47 anyCollection(),48 anyCollection(),49 anyCollection(),50 anyCollection());51 }52 @ParameterizedTest53 @MethodSource54 void getStep(final List<BattleStateVariation> parameters, final Order stepOrder) {55 final BattleState battleState = givenBattleState(parameters);56 final OffensiveFirstStrike offensiveFirstStrike =57 new OffensiveFirstStrike(battleState, battleActions);58 assertThat(offensiveFirstStrike.getNames(), hasSize(2));59 assertThat(offensiveFirstStrike.getOrder(), is(stepOrder));60 offensiveFirstStrike.execute(executionStack, delegateBridge);61 verify(battleActions)62 .findTargetGroupsAndFire(63 any(),64 anyString(),65 anyBoolean(),66 any(),67 any(),68 anyCollection(),69 anyCollection(),70 anyCollection(),71 anyCollection());72 }73 static List<Arguments> getStep() {74 return List.of(75 Arguments.of(76 List.of(BattleStateVariation.HAS_ATTACKING_FIRST_STRIKE), Order.FIRST_STRIKE_OFFENSIVE),77 Arguments.of(78 List.of(79 BattleStateVariation.HAS_ATTACKING_FIRST_STRIKE,80 BattleStateVariation.HAS_DEFENDING_DESTROYER),81 Order.FIRST_STRIKE_OFFENSIVE_REGULAR),82 Arguments.of(83 List.of(84 BattleStateVariation.HAS_ATTACKING_FIRST_STRIKE, BattleStateVariation.HAS_WW2V2),85 Order.FIRST_STRIKE_OFFENSIVE),...
Source:WildcardArgumentMatcherTest.java
...7import java.io.Serializable;8import java.util.Collections;9import static org.hamcrest.core.IsEqual.equalTo;10import static org.junit.Assert.assertThat;11import static org.mockito.ArgumentMatchers.anyCollection;12import static org.mockito.ArgumentMatchers.anyInt;13import static org.mockito.ArgumentMatchers.anyString;14import static org.mockito.ArgumentMatchers.eq;15import static org.mockito.ArgumentMatchers.isA;16import static org.mockito.Mockito.doNothing;17import static org.mockito.Mockito.reset;18import static org.mockito.Mockito.times;19import static org.mockito.Mockito.verify;20import static org.mockito.Mockito.when;21/**22 * program: myStudy23 * description: åæ°å¹é
æµè¯224 *25 * @author: alien26 * @since: 2019/11/23 20:4327 */28@RunWith(MockitoJUnitRunner.class)29public class WildcardArgumentMatcherTest {30 @Mock31 private SimpleService simpleService;32 /**33 * method name: WildcardMethod1 <br/>34 * description: åæ°å¹é
ä»»æå¼35 * @return: void36 * @since: 2019-11-2337 */38 @Test39 public void WildcardMethod1() {40 when(simpleService.method1(anyInt(), anyString(), anyCollection(), isA(Serializable.class))).thenReturn(100);41 int result = simpleService.method1(1, "Alex", Collections.emptyList(), "Mockito");42 assertThat(result, equalTo(100));43 result = simpleService.method1(1, "Alien", Collections.emptySet(), "MockitoForJava");44 assertThat(result, equalTo(100));45 }46 /**47 * method name: WildcardMethod1WithSpec <br/>48 * description: 第äºä¸ªåæ°å¹é
ç¹æ®æå®çå¼ï¼å
¶ä»åæ°å¹é
ä»»æå¼49 * @return: void50 * @since: 2019-11-2351 */52 @Test53 public void WildcardMethod1WithSpec() {54 // 以ä¸ç¬¬ä¸æ¡ä»£ç å¿
é¡»å¨ç¬¬äºæ¡å第ä¸æ¡åé¢ï¼å 为第ä¸æ¡çèå´æ¯å两æ¡å¤§55 // æ以第ä¸æ¡å¦æåå¨ç¬¬äºæ¡å第ä¸æ¡ä¹åå°±ä¼æ第äºæ¡å第ä¸æ¡çthenReturnç»æè¦çäº56 when(simpleService.method1(anyInt(), anyString(), anyCollection(), isA(Serializable.class))).thenReturn(-1);57 when(simpleService.method1(anyInt(), eq("Alex"), anyCollection(), isA(Serializable.class))).thenReturn(100);58 when(simpleService.method1(anyInt(), eq("Alien"), anyCollection(), isA(Serializable.class))).thenReturn(200);59 int result = simpleService.method1(1, "Alex", Collections.emptyList(), "Mockito");60 assertThat(result, equalTo(100));61 result = simpleService.method1(1, "Alien", Collections.emptySet(), "MockitoForJava");62 assertThat(result, equalTo(200));63 result = simpleService.method1(1, "dfadf", Collections.emptySet(), "MockitoForJava");64 assertThat(result, equalTo(-1));65 }66 /**67 * method name: WildcardMethod2 <br/>68 * description: æ è¿åå¼éªè¯69 * @return: void70 * @since: 2019-11-2371 */72 @Test73 public void WildcardMethod2() {74 doNothing().when(simpleService).method2(anyInt(), anyString(), anyCollection(), isA(Serializable.class));75 simpleService.method2(1, "Alex", Collections.emptyList(), "Mockito");76 verify(simpleService, times(1)).method2(1, "Alex", Collections.emptyList(), "Mockito");77 verify(simpleService, times(1)).method2(anyInt(), eq("Alex"), anyCollection(), isA(Serializable.class));78 }79 @After80 public void destory() {81 reset(simpleService);82 }83}...
Source:MockitoAnyTest.java
...56 model.setObject("s");57 //anyBoolean58 doCallRealMethod().when(model).setaBoolean(anyBoolean());59 model.setaBoolean(true);60 //anyCollection61 doCallRealMethod().when(model).setCollection(ArgumentMatchers.anyCollection());62 List list = new ArrayList();63 model.setCollection(list);64 //anyDouble65 doCallRealMethod().when(model).setaDouble(anyDouble());66 model.setaDouble(1d);67 //anyFloat68 doCallRealMethod().when(model).setaFloat(anyFloat());69 model.setaFloat(1f);70 //anyInt71 doCallRealMethod().when(model).setAnInt(anyInt());72 model.setAnInt(1);73 //anyList74 doCallRealMethod().when(model).setList(ArgumentMatchers.anyList());75 model.setList(list);...
Source:HealthCheckServiceTest.java
...7import org.mockito.Mock;8import org.mockito.junit.jupiter.MockitoExtension;9import java.io.IOException;10import static org.assertj.core.api.Assertions.assertThat;11import static org.mockito.ArgumentMatchers.anyCollection;12import static org.mockito.Mockito.when;13@ExtendWith(MockitoExtension.class)14class HealthCheckServiceTest {15 @Mock16 private SolrCloudHealthService solrCloudHealthServiceMock;17 @Mock18 private PostgreSqlHealthService postgreSqlHealthServiceMock;19 private HealthCheckService subject;20 private static final ImmutableSet<String> MOCK_SOLR_COLLECTIONS =21 ImmutableSet.of("mockCollection1", "mockCollection2");22 private static final ImmutableSet<String> MOCK_SOLR_COLLECTION_ALIAS = ImmutableSet.of("mockCollectionAlias");23 @BeforeEach24 void setUp() {25 subject = new HealthCheckService(solrCloudHealthServiceMock, postgreSqlHealthServiceMock);26 }27 @Test28 void solrCollectionsAreUp() throws IOException, SolrServerException {29 when(solrCloudHealthServiceMock.areCollectionsUp(anyCollection(), anyCollection())).thenReturn(true);30 assertThat(subject.isSolrUp(MOCK_SOLR_COLLECTIONS, MOCK_SOLR_COLLECTION_ALIAS)).isTrue();31 }32 @Test33 void solrCollectionsAreDown() throws IOException, SolrServerException {34 when(solrCloudHealthServiceMock.areCollectionsUp(anyCollection(), anyCollection())).thenReturn(false);35 assertThat(subject.isSolrUp(MOCK_SOLR_COLLECTIONS, MOCK_SOLR_COLLECTION_ALIAS)).isFalse();36 }37 @Test38 void solrThrowsException() throws IOException, SolrServerException {39 when(solrCloudHealthServiceMock.areCollectionsUp(anyCollection(), anyCollection()))40 .thenThrow(RuntimeException.class);41 assertThat(subject.isSolrUp(MOCK_SOLR_COLLECTIONS, MOCK_SOLR_COLLECTION_ALIAS)).isFalse();42 }43 @Test44 void experimentDaoThrowsException() {45 when(postgreSqlHealthServiceMock.isDatabaseUp()).thenThrow(RuntimeException.class);46 assertThat(subject.isDatabaseUp()).isFalse();47 }48}...
anyCollection
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anyCollection;2import static org.mockito.Mockito.times;3import static org.mockito.Mockito.verify;4import static org.mockito.Mockito.when;5import java.util.ArrayList;6import java.util.List;7import org.junit.Test;8import org.junit.runner.RunWith;9import org.mockito.Mock;10import org.mockito.junit.MockitoJUnitRunner;11@RunWith(MockitoJUnitRunner.class)12public class MockitoAnyCollection {13 private List<String> mockedList;14 public void testAnyCollection() {15 when(mockedList.addAll(anyCollection())).thenReturn(true);16 mockedList.addAll(new ArrayList<String>());17 verify(mockedList, times(1)).addAll(anyCollection());18 }19}20Related posts: Mockito anyList() method example Mockito anyInt() method example Mockito anyVararg() method example Mockito anyObject() method example Mockito anyString() method example Mockito any() method example Mockito anySet() method example Mockito anyMap() method example Mockito anyCollection() method example Mockito anyIterable() method example Mockito anyClass() method example Mockito anyBoolean() method example Mockito anyByte() method example Mockito anyChar() method example Mockito anyDouble() method example Mockito anyFloat() method example Mockito anyLong() method example Mockito anyShort() method example Mockito anyVararg() method example Mockito any() method example Mockito anyList() method example Mockito anySet() method example Mockito anyMap() method example Mockito anyCollection() method example Mockito anyIterable() method example Mockito anyClass() method example Mockito anyString() method example Mockito anyInt() method example Mockito anyBoolean() method example Mockito anyByte() method example Mockito anyChar() method example Mockito anyDouble() method example Mockito anyFloat() method example Mockito anyLong() method example Mockito anyShort() method example Mockito anyObject() method example Mockito any() method example Mockito anyList() method example Mockito anySet() method example Mockito anyMap() method example Mockito anyCollection() method example Mockito anyIterable() method example Mockito anyClass() method example Mockito anyString() method example Mockito anyInt() method example Mockito anyBoolean() method example Mockito anyByte() method example Mockito anyChar() method example Mockito anyDouble() method example Mockito anyFloat() method example Mockito anyLong() method example Mockito anyShort() method example Mockito anyObject() method example Mockito any() method example Mockito anyList() method example Mockito anySet() method example Mockito anyMap() method example Mockito anyCollection() method example Mockito anyIterable
anyCollection
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import static org.mockito.ArgumentMatchers.anyCollection;3import static org.mockito.ArgumentMatchers.anyList;4import static org.mockito.ArgumentMatchers.anySet;5import static org.mockito.ArgumentMatchers.anyMap;6import static org.mockito.ArgumentMatchers.any;7import java.util.List;8import java.util.Map;9import java.util.Set;10import java.util.Collection;11import java.util.ArrayList;12import java.util.HashMap;13import java.util.HashSet;14import org.mockito.Mockito;15import org.mockito.invocation.InvocationOnMock;16import org.mockito.stubbing.Answer;17import org.mockito.stubbing.OngoingStubbing;18import org.mockito.stubbing.Stubber;19class Test {20 public static void main(String[] args) {21 Test t = new Test();22 t.test1();23 t.test2();24 t.test3();25 t.test4();26 }27 public void test1() {28 List<String> list = Mockito.mock(List.class);29 Mockito.when(list.get(anyInt())).thenReturn("Hello");30 System.out.println("test1: " + list.get(5));31 }32 public void test2() {33 List<String> list = Mockito.mock(List.class);34 Mockito.when(list.get(anyInt())).thenReturn("Hello");35 System.out.println("test2: " + list.get(5));36 }37 public void test3() {38 List<String> list = Mockito.mock(List.class);39 Mockito.when(list.get(anyInt())).thenReturn("Hello");40 System.out.println("test3: " + list.get(5));41 }42 public void test4() {43 List<String> list = Mockito.mock(List.class);44 Mockito.when(list.get(anyInt())).thenReturn("Hello");45 System.out.println("test4: " + list.get(5));46 }47}
anyCollection
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anyCollection;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.when;4import java.util.ArrayList;5import java.util.List;6public class anyCollectionExample {7 public static void main(String[] args) {8 List mockedList = mock(List.class);9 when(mockedList.addAll(anyCollection())).thenReturn(true);10 System.out.println(mockedList.addAll(new ArrayList()));11 System.out.println(mockedList.addAll(null));12 }13}14import static org.mockito.ArgumentMatchers.anyCollectionOf;15import static org.mockito.Mockito.mock;16import static org.mockito.Mockito.when;17import java.util.ArrayList;18import java.util.List;19public class anyCollectionOfExample {20 public static void main(String[] args) {21 List mockedList = mock(List.class);22 when(mockedList.addAll(anyCollectionOf(ArrayList.class))).thenReturn(true);23 System.out.println(mockedList.addAll(new ArrayList()));24 System.out.println(mockedList.addAll(null));25 }26}27import static org.mockito.ArgumentMatchers.anyList;28import static org.mockito.Mockito.mock;29import static org.mockito.Mockito.when;30import java.util.ArrayList;31import java.util.List;32public class anyListExample {33 public static void main(String[] args) {34 List mockedList = mock(List.class);35 when(mockedList.addAll(anyList())).thenReturn(true);36 System.out.println(mockedList.addAll(new ArrayList()));37 System.out.println(mockedList.addAll(null));38 }39}40import static org.mockito.ArgumentMatchers.anyMap;41import static org.mockito.Mockito.mock;42import
anyCollection
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anyCollection;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.verify;4import java.util.ArrayList;5import java.util.Collection;6import java.util.List;7public class Example {8 public static void main(String[] args) {9 List<String> mockedList = mock(List.class);10 mockedList.addAll(new ArrayList<String>());11 mockedList.addAll(new ArrayList<String>());12 verify(mockedList).addAll(anyCollection());13 }14}15Argument(s) are different! Wanted:16mockedList.addAll(17);18-> at com.example.Example.main(Example.java:22)19mockedList.addAll(20);21-> at com.example.Example.main(Example.java:20)22import static org.mockito.ArgumentMatchers.sameCollection;23import static org.mockito.Mockito.mock;24import static org.mockito.Mockito.verify;25import java.util.ArrayList;26import java.util.Collection;27import java.util.List;28public class Example {29 public static void main(String[] args) {30 List<String> mockedList = mock(List.class);31 Collection<String> col = new ArrayList<String>();32 mockedList.addAll(col);33 mockedList.addAll(col);34 verify(mockedList).addAll(sameCollection(col));35 }36}37Argument(s) are different! Wanted:38mockedList.addAll(39);40-> at com.example.Example.main(Example.java:23)41mockedList.addAll(42);43-> at com.example.Example.main(Example.java:20)
anyCollection
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3import java.util.ArrayList;4import java.util.List;5public class anyCollection {6 public static void main(String[] args) {7 List<String> list = new ArrayList<>();8 list.add("one");9 list.add("two");10 list.add("three");11 List<String> list1 = Mockito.mock(ArrayList.class);12 Mockito.when(list1.addAll(ArgumentMatchers.anyCollection())).thenReturn(true);13 System.out.println(list1.addAll(list));14 }15}
anyCollection
Using AI Code Generation
1import java.util.*;2import org.mockito.ArgumentMatchers;3import org.mockito.Mockito;4public class AnyCollection {5 public static void main(String[] args) {6 List<String> list = new ArrayList<>();7 list.add("one");8 list.add("two");9 list.add("three");10 list.add("four");11 list.add("five");12 List<String> list1 = Mockito.mock(List.class);13 Mockito.when(list1.get(ArgumentMatchers.anyInt())).thenReturn("one");14 System.out.println(list1.get(0));15 System.out.println(list1.get(1));16 List<String> list2 = Mockito.mock(List.class);17 Mockito.when(list2.get(ArgumentMatchers.anyInt())).thenReturn("two");18 System.out.println(list2.get(0));19 System.out.println(list2.get(1));20 Mockito.when(list1.get(ArgumentMatchers.anyInt())).thenReturn("three");21 System.out.println(list1.get(0));22 System.out.println(list1.get(1));23 Mockito.when(list2.get(ArgumentMatchers.anyInt())).thenReturn("four");24 System.out.println(list2.get(0));25 System.out.println(list2.get(1));26 Mockito.when(list1.get(ArgumentMatchers.anyInt())).thenReturn("five");27 System.out.println(list1.get(0));28 System.out.println(list1.get(1));29 Mockito.when(list2.get(ArgumentMatchers.anyInt())).thenReturn("six");30 System.out.println(list2.get(0));31 System.out.println(list2.get(1));32 }33}34Recommended Posts: Mockito - anyBoolean() Method35Mockito - anyInt() Method36Mockito - anyLong() Method37Mockito - anyFloat() Method38Mockito - anyDouble() Method39Mockito - anyString() Method40Mockito - any() Method41Mockito - anyObject() Method42Mockito - anyVararg() Method43Mockito - anyCollection() Method44Mockito - anyList() Method45Mockito - anySet() Method46Mockito - anyMap() Method47Mockito - anyIterable() Method48Mockito - anyIterator() Method49Mockito - anyClass() Method50Mockito - anyVararg() Method51Mockito - anyCollection() Method
anyCollection
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mock;3import org.mockito.Mockito;4import org.mockito.MockitoAnnotations;5import org.mockito.stubbing.Answer;6import java.util.List;7public class anyCollection {8 List<String> list;9 public static void main(String[] args) {10 anyCollection anyCollection = new anyCollection();11 anyCollection.anyCollectionMethod();12 }13 public void anyCollectionMethod() {14 MockitoAnnotations.initMocks(this);15 Mockito.when(list.addAll(ArgumentMatchers.anyCollection())).thenAnswer((Answer) invocation -> {16 Object[] args = invocation.getArguments();17 Object mock = invocation.getMock();18 return true;19 });20 list.addAll(null);21 }22}23Recommended Posts: Mockito - anyCollection() method24Mockito - anyInt() method25Mockito - any() method26Mockito - anyString() method27Mockito - anyList() method28Mockito - anySet() method29Mockito - anyMap() method30Mockito - anyVararg() method31Mockito - anyBoolean() method32Mockito - anyDouble() method33Mockito - anyFloat() method34Mockito - anyLong() method35Mockito - anyByte() method36Mockito - anyChar() method37Mockito - anyShort() method38Mockito - anyObject() method39Mockito - anyCollectionOf() method40Mockito - anyIterable() method41Mockito - anyVararg() method42Mockito - anyList() method43Mockito - anySet() method44Mockito - anyMap() method45Mockito - anyCollection() method
anyCollection
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import java.util.Collection;3import java.util.List;4import java.util.ArrayList;5import java.util.Arrays;6import java.util.Collections;7import java.util.HashSet;8import java.util.Set;9import java.util.TreeSet;10import java.util.concurrent.CopyOnWriteArrayList;11import java.util.concurrent.CopyOnWriteArraySet;12import java.util.stream.Collectors;13import java.util.stream.Stream;14import java.util.stream.IntStream;15import java.util.stream.LongStream;16import java.util.stream.DoubleStream;17import java.util.stream.StreamSupport;18import java.util.stream.IntStream;19import java.util.stream.LongStream;20import java.util.stream.DoubleStream;21import java.util.stream.StreamSupport;22import java.util.stream.IntStream;23import java.util.stream.LongStream;24import java.util.stream.DoubleStream;25import java.util.stream.StreamSupport;26import java.util.stream.IntStream;27import java.util.stream.LongStream;28import java.util.stream.DoubleStream;29import java.util.stream.StreamSupport;30import java.util.stream.IntStream;31import java.util.stream.LongStream;32import java.util.stream.DoubleStream;33import java.util.stream.StreamSupport;34import java.util.stream.IntStream;35import java.util.stream.LongStream;36import java.util.stream.DoubleStream;37import java.util.stream.StreamSupport;38import java.util.stream.IntStream;39import java.util.stream.LongStream;40import java.util.stream.DoubleStream;41import java.util.stream.StreamSupport;42import java.util.stream.IntStream;43import java.util.stream.LongStream;44import java.util.stream.DoubleStream;45import java.util.stream.StreamSupport;46import java.util.stream.IntStream;47import java.util.stream.LongStream;48import java.util.stream.DoubleStream;49import java.util.stream.StreamSupport;50import java.util.stream.IntStream;51import java.util.stream.LongStream;52import java.util.stream.DoubleStream;53import java.util.stream.StreamSupport;54import java.util.stream.IntStream;55import java.util.stream.LongStream;56import java.util.stream.DoubleStream;57import java.util.stream.StreamSupport;58import java.util.stream.IntStream;59import java.util.stream.LongStream;60import java.util.stream.DoubleStream;61import java.util.stream.StreamSupport;62import java.util.stream.IntStream;63import java.util.stream.LongStream;64import java.util.stream.DoubleStream;65import java.util.stream.StreamSupport;66import java.util.stream.IntStream;67import java.util.stream.LongStream;68import java.util.stream.DoubleStream;69import java.util.stream.StreamSupport;70import java.util.stream.IntStream;71import java.util.stream.LongStream;72import java.util.stream.DoubleStream;73import java.util.stream.StreamSupport;
anyCollection
Using AI Code Generation
1import java.util.*;2import org.mockito.*;3public class anyCollection {4 public static void main(String[] args) {5 List mockList = Mockito.mock(List.class);6 Mockito.when(mockList.addAll(Mockito.anyCollection())).thenReturn(true);7 mockList.addAll(Arrays.asList("one", "two", "three"));8 Mockito.verify(mockList).addAll(Mockito.anyCollection());9 }10}11import java.util.*;12import org.mockito.*;13public class anyCollectionOf {14 public static void main(String[] args) {15 List mockList = Mockito.mock(List.class);16 Mockito.when(mockList.addAll(Mockito.anyCollectionOf(Collection.class))).thenReturn(true);17 mockList.addAll(Arrays.asList("one", "two", "three"));18 Mockito.verify(mockList).addAll(Mockito.anyCollectionOf(Collection.class));19 }20}21import java.util.*;22import org.mockito.*;23public class anyList {24 public static void main(String[] args) {25 List mockList = Mockito.mock(List.class);26 Mockito.when(mockList.addAll(Mockito.anyList())).thenReturn(true);27 mockList.addAll(Arrays.asList("one", "two", "three"));28 Mockito.verify(mockList).addAll(Mockito.anyList());29 }30}31import java.util.*;32import org.mockito.*;33public class anySet {34 public static void main(String[] args) {35 Set mockSet = Mockito.mock(Set.class);36 Mockito.when(mockSet.addAll(Mockito.anySet())).thenReturn(true);37 mockSet.addAll(new HashSet<>(Arrays.asList("one", "two", "three")));38 Mockito.verify(mockSet).addAll(Mockito.anySet());39 }40}
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!!