Best Mockito code snippet using org.mockito.ArgumentMatchers.anySetOf
Source:UserProfileManagerImplUnitTest.java
...7import static org.junit.jupiter.api.Assertions.assertTrue;8import static org.junit.jupiter.api.Assertions.fail;9import static org.mockito.ArgumentMatchers.any;10import static org.mockito.ArgumentMatchers.anyInt;11import static org.mockito.ArgumentMatchers.anySetOf;12import static org.mockito.ArgumentMatchers.anyString;13import static org.mockito.ArgumentMatchers.eq;14import static org.mockito.Mockito.never;15import static org.mockito.Mockito.times;16import static org.mockito.Mockito.verify;17import static org.mockito.Mockito.when;18import java.util.ArrayList;19import java.util.Collections;20import java.util.List;21import java.util.Set;22import org.junit.jupiter.api.BeforeEach;23import org.junit.jupiter.api.Test;24import org.junit.jupiter.api.extension.ExtendWith;25import org.mockito.InjectMocks;26import org.mockito.Mock;27import org.mockito.Mockito;28import org.mockito.invocation.InvocationOnMock;29import org.mockito.junit.jupiter.MockitoExtension;30import org.mockito.stubbing.Answer;31import org.sagebionetworks.repo.manager.file.FileHandleManager;32import org.sagebionetworks.repo.manager.file.FileHandleUrlRequest;33import org.sagebionetworks.repo.model.AuthorizationConstants.BOOTSTRAP_PRINCIPAL;34import org.sagebionetworks.repo.model.Favorite;35import org.sagebionetworks.repo.model.FavoriteDAO;36import org.sagebionetworks.repo.model.IdList;37import org.sagebionetworks.repo.model.NextPageToken;38import org.sagebionetworks.repo.model.NodeDAO;39import org.sagebionetworks.repo.model.ProjectHeaderList;40import org.sagebionetworks.repo.model.ProjectListSortColumn;41import org.sagebionetworks.repo.model.ProjectListType;42import org.sagebionetworks.repo.model.UnauthorizedException;43import org.sagebionetworks.repo.model.UserGroupDAO;44import org.sagebionetworks.repo.model.UserInfo;45import org.sagebionetworks.repo.model.UserProfile;46import org.sagebionetworks.repo.model.UserProfileDAO;47import org.sagebionetworks.repo.model.auth.AuthorizationStatus;48import org.sagebionetworks.repo.model.dbo.dao.UserProfileUtils;49import org.sagebionetworks.repo.model.dbo.persistence.DBOUserProfile;50import org.sagebionetworks.repo.model.entity.query.SortDirection;51import org.sagebionetworks.repo.model.favorite.SortBy;52import org.sagebionetworks.repo.model.file.FileHandleAssociateType;53import org.sagebionetworks.repo.model.message.Settings;54import org.sagebionetworks.repo.model.principal.AliasType;55import org.sagebionetworks.repo.model.principal.PrincipalAlias;56import org.sagebionetworks.repo.model.principal.PrincipalAliasDAO;57import org.sagebionetworks.repo.web.NotFoundException;58import com.google.common.collect.Sets;59@ExtendWith(MockitoExtension.class)60public class UserProfileManagerImplUnitTest {61 @Mock62 UserProfileDAO mockProfileDAO;63 @Mock64 UserGroupDAO mockUserGroupDAO;65 @Mock66 UserManager mockUserManager;67 @Mock68 FavoriteDAO mockFavoriteDAO;69 @Mock70 PrincipalAliasDAO mockPrincipalAliasDAO;71 @Mock72 AuthorizationManager mockAuthorizationManager;73 @Mock74 FileHandleManager mockFileHandleManager;75 @Mock76 NodeDAO mockNodeDao;77 @InjectMocks78 UserProfileManagerImpl userProfileManager;79 80 UserInfo userInfo;81 UserInfo adminUserInfo;82 UserProfile userProfile;83 UserInfo caller;84 85 @Mock86 UserInfo userToGetFor;87 88 Long teamToFetchId;89 ProjectListType type;90 ProjectListSortColumn sortColumn;91 SortDirection sortDirection;92 String nextPageToken;93 Set<Long> visibleProjectsOne;94 Set<Long> visibleProjectsTwo;95 Set<Long> callersGroups;96 Set<Long> userToGetForGroups;97 List<PrincipalAlias> aliases;98 99 private static final Long userId = 9348725L;100 private static final Long adminUserId = 823746L;101 private static final String USER_EMAIL = "foo@bar.org";102 private static final String USER_OPEN_ID = "http://myspace.com/foo";103 private static final Long LIMIT_FOR_QUERY = NextPageToken.DEFAULT_LIMIT+1;104 private static final Long OFFSET = NextPageToken.DEFAULT_OFFSET;105 @BeforeEach106 public void before() throws Exception {107 userInfo = new UserInfo(false, userId);108 adminUserInfo = new UserInfo(true, adminUserId);109 110 userProfile = new UserProfile();111 userProfile.setOwnerId(userInfo.getId().toString());112 userProfile.setRStudioUrl("myPrivateRStudioUrl");113 userProfile.setUserName("TEMPORARY-111");114 userProfile.setLocation("I'm guessing this is private");115 userProfile.setOpenIds(Collections.singletonList(USER_OPEN_ID));116 userProfile.setEmails(Collections.singletonList(USER_EMAIL));117 Settings settings = new Settings();118 settings.setSendEmailNotifications(true);119 userProfile.setNotificationSettings(settings);120 121 PrincipalAlias alias = new PrincipalAlias();122 alias.setAlias(USER_EMAIL);123 alias.setPrincipalId(userId);124 alias.setType(AliasType.USER_EMAIL);125 aliases = new ArrayList<PrincipalAlias>();126 aliases.add(alias);127 alias = new PrincipalAlias();128 alias.setAlias(USER_OPEN_ID);129 alias.setPrincipalId(userId);130 alias.setType(AliasType.USER_OPEN_ID);131 aliases.add(alias);132 caller = new UserInfo(false, 123L);133 callersGroups = Sets.newHashSet(1L, 2L, 3L, caller.getId(),134 BOOTSTRAP_PRINCIPAL.PUBLIC_GROUP.getPrincipalId(),135 BOOTSTRAP_PRINCIPAL.AUTHENTICATED_USERS_GROUP.getPrincipalId(),136 BOOTSTRAP_PRINCIPAL.CERTIFIED_USERS.getPrincipalId());137 caller.setGroups(callersGroups);138 userToGetForGroups = Sets.newHashSet(4L, 5L, 6L,139 userToGetFor.getId(),140 BOOTSTRAP_PRINCIPAL.PUBLIC_GROUP.getPrincipalId(),141 BOOTSTRAP_PRINCIPAL.AUTHENTICATED_USERS_GROUP.getPrincipalId(),142 BOOTSTRAP_PRINCIPAL.CERTIFIED_USERS.getPrincipalId());143 teamToFetchId = null;144 type = ProjectListType.CREATED;145 sortColumn = ProjectListSortColumn.LAST_ACTIVITY;146 sortDirection = SortDirection.ASC;147 nextPageToken = (new NextPageToken(null)).toToken();148 149 visibleProjectsOne = Sets.newHashSet(111L,222L,333L);150 visibleProjectsTwo = Sets.newHashSet(222L,333L,444L);151 }152 153 @Test154 public void testUpdateProfileFileHandleAuthrorized() throws NotFoundException{155 // UserProfileDAO should return a copy of the mock UserProfile when getting156 Mockito.doAnswer(new Answer<UserProfile>() {157 @Override158 public UserProfile answer(InvocationOnMock invocation) throws Throwable {159 DBOUserProfile intermediate = new DBOUserProfile();160 UserProfileUtils.copyDtoToDbo(userProfile, intermediate);161 UserProfile copy = UserProfileUtils.convertDboToDto(intermediate);162 return copy;163 }164 }).when(mockProfileDAO).get(Mockito.anyString());165 166 String fileHandleId = "123";167 when(mockAuthorizationManager.canAccessRawFileHandleById(userInfo, fileHandleId)).thenReturn(AuthorizationStatus.authorized());168 UserProfile profile = new UserProfile();169 profile.setOwnerId(""+userInfo.getId());170 profile.setUserName("some username");171 profile.setProfilePicureFileHandleId(fileHandleId);172 userProfileManager.updateUserProfile(userInfo, profile);173 verify(mockProfileDAO).update(any(UserProfile.class));174 }175 176 @Test177 public void testUpdateProfileFileHandleUnAuthrorized() throws NotFoundException{ 178 String fileHandleId = "123";179 when(mockAuthorizationManager.canAccessRawFileHandleById(userInfo, fileHandleId)).thenReturn(AuthorizationStatus.accessDenied("User does not own the file handle"));180 UserProfile profile = new UserProfile();181 profile.setOwnerId(""+userInfo.getId());182 profile.setUserName("some username");183 profile.setProfilePicureFileHandleId(fileHandleId);184 assertThrows(UnauthorizedException.class, () -> {185 userProfileManager.updateUserProfile(userInfo, profile);186 });187 }188 189 @Test190 public void testAddFavorite() throws Exception { 191 String entityId = "syn123";192 userProfileManager.addFavorite(userInfo, entityId);193 Favorite fav = new Favorite();194 fav.setPrincipalId(userInfo.getId().toString());195 fav.setEntityId(entityId);196 verify(mockFavoriteDAO).add(fav);197 }198 199 @Test200 public void testAddFavoriteAsAnonymous() throws Exception {201 String entityId = "syn123";202 when(mockAuthorizationManager.isAnonymousUser(userInfo)).thenReturn(true);203 assertThrows(UnauthorizedException.class, ()->{204 userProfileManager.addFavorite(userInfo, entityId);205 });206 }207 208 @Test209 public void testRemoveFavoriteAsAnonymous() throws Exception {210 String entityId = "syn123";211 when(mockAuthorizationManager.isAnonymousUser(userInfo)).thenReturn(true);212 assertThrows(UnauthorizedException.class, ()->{213 userProfileManager.removeFavorite(userInfo, entityId);214 });215 }216 217 @Test218 public void testGetFavoriteAsAnonymous() throws Exception {219 when(mockAuthorizationManager.isAnonymousUser(userInfo)).thenReturn(true);220 assertTrue(221 userProfileManager.getFavorites(userInfo, 10, 0, SortBy.FAVORITED_ON, org.sagebionetworks.repo.model.favorite.SortDirection.ASC).getResults().isEmpty()222 );223 verify(mockFavoriteDAO, never()).getFavoritesEntityHeader(anyString(), anyInt(), anyInt(), any(SortBy.class), any(org.sagebionetworks.repo.model.favorite.SortDirection.class));224 }225 226 /* Tests moved and mocked from UserProfileManagerImplTest */227 228 @Test229 public void testGetOwnUserProfile() throws Exception {230 // UserProfileDAO should return a copy of the mock UserProfile when getting231 Mockito.doAnswer(new Answer<UserProfile>() {232 @Override233 public UserProfile answer(InvocationOnMock invocation) throws Throwable {234 DBOUserProfile intermediate = new DBOUserProfile();235 UserProfileUtils.copyDtoToDbo(userProfile, intermediate);236 UserProfile copy = UserProfileUtils.convertDboToDto(intermediate);237 return copy;238 }239 }).when(mockProfileDAO).get(Mockito.anyString());240 241 when(mockPrincipalAliasDAO.listPrincipalAliases(userId)).thenReturn(aliases);242 243 String ownerId = userInfo.getId().toString();244 UserProfile upClone = userProfileManager.getUserProfile(ownerId);245 assertEquals(userProfile, upClone);246 }247 248 @Test249 public void getAll() throws Exception {250 when(mockPrincipalAliasDAO.listPrincipalAliases(Collections.singleton(userId))).thenReturn(aliases);251 252 UserProfile upForList = new UserProfile();253 upForList.setOwnerId(userProfile.getOwnerId());254 upForList.setRStudioUrl(userProfile.getRStudioUrl());255 upForList.setUserName(userProfile.getUserName());256 upForList.setLocation(userProfile.getLocation());257 upForList.setEmails(userProfile.getEmails());258 upForList.setOpenIds(userProfile.getOpenIds());259 260 List<UserProfile> upList = Collections.singletonList(upForList);261 when(mockProfileDAO.getInRange(0L, 1L)).thenReturn(upList);262 when(mockProfileDAO.list(Collections.singletonList(Long.parseLong(userProfile.getOwnerId())))).263 thenReturn(upList);264 List<UserProfile> results=userProfileManager.getInRange(adminUserInfo, 0, 1);265 assertFalse(upForList.getEmails().isEmpty());266 assertFalse(upForList.getOpenIds().isEmpty());267 assertEquals(upList, results);268 269 IdList ids = new IdList();270 ids.setList(Collections.singletonList(Long.parseLong(userProfile.getOwnerId())));271 assertEquals(results, userProfileManager.list(ids).getList());272 }273 274 @Test275 public void testGetOthersUserProfileByAdmin() throws Exception {276 // UserProfileDAO should return a copy of the mock UserProfile when getting277 Mockito.doAnswer(new Answer<UserProfile>() {278 @Override279 public UserProfile answer(InvocationOnMock invocation) throws Throwable {280 DBOUserProfile intermediate = new DBOUserProfile();281 UserProfileUtils.copyDtoToDbo(userProfile, intermediate);282 UserProfile copy = UserProfileUtils.convertDboToDto(intermediate);283 return copy;284 }285 }).when(mockProfileDAO).get(Mockito.anyString());286 287 when(mockPrincipalAliasDAO.listPrincipalAliases(userId)).thenReturn(aliases);288 289 String ownerId = userInfo.getId().toString();290 UserProfile upClone = userProfileManager.getUserProfile(ownerId);291 assertEquals(userProfile, upClone);292 }293 294 @Test295 public void testUpdateOthersUserProfile() throws Exception {296 // UserProfileDAO should return a copy of the mock UserProfile when getting297 Mockito.doAnswer(new Answer<UserProfile>() {298 @Override299 public UserProfile answer(InvocationOnMock invocation) throws Throwable {300 DBOUserProfile intermediate = new DBOUserProfile();301 UserProfileUtils.copyDtoToDbo(userProfile, intermediate);302 UserProfile copy = UserProfileUtils.convertDboToDto(intermediate);303 return copy;304 }305 }).when(mockProfileDAO).get(Mockito.anyString());306 307 when(mockPrincipalAliasDAO.listPrincipalAliases(userId)).thenReturn(aliases);308 309 String ownerId = userInfo.getId().toString();310 userInfo.setId(-100L);311 312 UserProfile upClone = userProfileManager.getUserProfile(ownerId);313 // so we get back the UserProfile for the specified owner...314 assertEquals(ownerId, upClone.getOwnerId());315 // ... but we can't update it, since we are not the owner or an admin316 // the following step will fail317 assertThrows(UnauthorizedException.class, () -> {318 userProfileManager.updateUserProfile(userInfo, upClone);319 });320 }321 322 @Test323 public void testUpdateAnonymousUserProfile() throws Exception {324 when(mockAuthorizationManager.isAnonymousUser(userInfo)).thenReturn(true);325 326 assertThrows(UnauthorizedException.class, () -> {327 userProfileManager.updateUserProfile(userInfo, userProfile);328 });329 330 verify(mockProfileDAO, never()).update(any(UserProfile.class));331 }332 333 @Test334 public void testGetGroupsMinusPublic(){335 Set<Long> results = UserProfileManagerImpl.getGroupsMinusPublic(caller.getGroups());336 // should get a new copy337 assertFalse(results == caller.getGroups());338 assertEquals(caller.getGroups().size()-3, results.size());339 // the following groups should have been removed.340 assertFalse(results.contains(BOOTSTRAP_PRINCIPAL.PUBLIC_GROUP.getPrincipalId()));341 assertFalse(results.contains(BOOTSTRAP_PRINCIPAL.AUTHENTICATED_USERS_GROUP.getPrincipalId()));342 assertFalse(results.contains(BOOTSTRAP_PRINCIPAL.CERTIFIED_USERS.getPrincipalId()));343 // The user's id should still be in the set344 assertTrue(results.contains(caller.getId()));345 }346 347 @Test348 public void testGetGroupsMinusPublicAndSelf(){ 349 Set<Long> results = UserProfileManagerImpl.getGroupsMinusPublicAndSelf(caller.getGroups(), caller.getId());350 // should get a new copy351 assertFalse(results == caller.getGroups());352 assertEquals(caller.getGroups().size()-4, results.size());353 // the following groups should have been removed.354 assertFalse(results.contains(BOOTSTRAP_PRINCIPAL.PUBLIC_GROUP.getPrincipalId()));355 assertFalse(results.contains(BOOTSTRAP_PRINCIPAL.AUTHENTICATED_USERS_GROUP.getPrincipalId()));356 assertFalse(results.contains(BOOTSTRAP_PRINCIPAL.CERTIFIED_USERS.getPrincipalId()));357 // The user's id should also be removed358 assertFalse(results.contains(caller.getId()));359 }360 361 /**362 * For this case the caller is not an admin, and the caller363 * and the userToGetFor are different.364 */365 @Test366 public void testGetProjectsNonAdminCallerDifferent(){ 367 when(userToGetFor.getId()).thenReturn(456L);368 when(userToGetFor.getGroups()).thenReturn(userToGetForGroups);369 370 when(mockAuthorizationManager.getAccessibleProjectIds(anySetOf(Long.class))).thenReturn(371 visibleProjectsOne,372 visibleProjectsTwo373 ); 374 375 // call under test376 ProjectHeaderList results = userProfileManager.getProjects(377 caller, userToGetFor, teamToFetchId, type, sortColumn, sortDirection, nextPageToken);378 assertNotNull(results);379 assertNotNull(results.getResults());380 assertNull(results.getNextPageToken());381 // Accessible projects should be called once for the userToGetFor and once for the caller.382 verify(mockAuthorizationManager, times(2)).getAccessibleProjectIds(anySetOf(Long.class));383 // the groups for the userToGetFor should exclude public.384 Set<Long> expectedUserToGetGroups = UserProfileManagerImpl.getGroupsMinusPublic(userToGetFor.getGroups());385 verify(mockAuthorizationManager).getAccessibleProjectIds(expectedUserToGetGroups);386 verify(mockAuthorizationManager).getAccessibleProjectIds(caller.getGroups());387 // The projectIds passed to the dao should be the intersection of the caller's projects388 // and the userToGetFor's projects.389 Set<Long> expectedProjectIds = Sets.intersection(visibleProjectsOne, visibleProjectsTwo);390 verify(mockNodeDao).getProjectHeaders(userToGetFor.getId(), expectedProjectIds, type, sortColumn, sortDirection, LIMIT_FOR_QUERY, OFFSET);391 }392 393 /**394 * For this case the caller is not an admin, and the caller395 * and the userToGetFor are the same.396 */397 @Test398 public void testGetProjectsNonAdminCallerSame(){399 when(userToGetFor.getId()).thenReturn(456L);400 when(userToGetFor.isAdmin()).thenReturn(false);401 when(userToGetFor.getGroups()).thenReturn(userToGetForGroups);402 403 when(mockAuthorizationManager.getAccessibleProjectIds(anySetOf(Long.class))).thenReturn(404 visibleProjectsOne,405 visibleProjectsTwo406 ); 407 408 // the caller is the same as the userToGetFor.409 caller = userToGetFor;410 // call under test411 ProjectHeaderList results = userProfileManager.getProjects(412 caller, userToGetFor, teamToFetchId, type, sortColumn, sortDirection, nextPageToken);413 assertNotNull(results);414 // Accessible projects should only be called once for the userToGetFor.415 verify(mockAuthorizationManager, times(1)).getAccessibleProjectIds(anySetOf(Long.class));416 // the groups for the userToGetFor should exclude public.417 Set<Long> expectedUserToGetGroups = UserProfileManagerImpl.getGroupsMinusPublic(userToGetFor.getGroups());418 verify(mockAuthorizationManager).getAccessibleProjectIds(expectedUserToGetGroups);419 // The projectIds passed to the dao should be the same as userToGetFor can see.420 Set<Long> expectedProjectIds = visibleProjectsOne;421 verify(mockNodeDao).getProjectHeaders(caller.getId(), expectedProjectIds, type, sortColumn, sortDirection, LIMIT_FOR_QUERY, OFFSET);422 }423 424 /**425 * For this case the caller is an admin, and the caller426 * and the userToGetFor are different.427 */428 @Test429 public void testGetProjectsAdminCallerDifferent(){ 430 when(userToGetFor.getId()).thenReturn(456L);431 when(userToGetFor.getGroups()).thenReturn(userToGetForGroups);432 433 when(mockAuthorizationManager.getAccessibleProjectIds(anySetOf(Long.class))).thenReturn(434 visibleProjectsOne,435 visibleProjectsTwo436 ); 437 438 // call under test439 ProjectHeaderList results = userProfileManager.getProjects(440 adminUserInfo, userToGetFor, teamToFetchId, type, sortColumn, sortDirection, nextPageToken);441 assertNotNull(results);442 // Accessible projects should only be called once the userToGetFor443 verify(mockAuthorizationManager, times(1)).getAccessibleProjectIds(anySetOf(Long.class));444 // the groups for the userToGetFor should exclude public.445 Set<Long> expectedUserToGetGroups = UserProfileManagerImpl.getGroupsMinusPublic(userToGetFor.getGroups());446 verify(mockAuthorizationManager).getAccessibleProjectIds(expectedUserToGetGroups);447 // The projectIds passed to the dao should be the same as userToGetFor can see.448 Set<Long> expectedProjectIds = visibleProjectsOne;449 verify(mockNodeDao).getProjectHeaders(userToGetFor.getId(), expectedProjectIds, type, sortColumn, sortDirection, LIMIT_FOR_QUERY, OFFSET);450 }451 452 /**453 * For this case the caller is an admin, and the caller454 * and the userToGetFor are different.455 */456 @Test457 public void testGetProjectsAdminCallerSame(){458 when(userToGetFor.getId()).thenReturn(456L);459 when(userToGetFor.isAdmin()).thenReturn(false);460 when(userToGetFor.getGroups()).thenReturn(userToGetForGroups);461 462 when(mockAuthorizationManager.getAccessibleProjectIds(anySetOf(Long.class))).thenReturn(463 visibleProjectsOne,464 visibleProjectsTwo465 ); 466 467 caller = userToGetFor;468 when(caller.isAdmin()).thenReturn(true);469 // call under test470 ProjectHeaderList results = userProfileManager.getProjects(471 caller, userToGetFor, teamToFetchId, type, sortColumn, sortDirection, nextPageToken);472 assertNotNull(results);473 // Accessible projects should only be called once the userToGetFor474 verify(mockAuthorizationManager, times(1)).getAccessibleProjectIds(anySetOf(Long.class));475 // the groups for the userToGetFor should exclude public.476 Set<Long> expectedUserToGetGroups = UserProfileManagerImpl.getGroupsMinusPublic(userToGetFor.getGroups());477 verify(mockAuthorizationManager).getAccessibleProjectIds(expectedUserToGetGroups);478 // The projectIds passed to the dao should be the same as userToGetFor can see.479 Set<Long> expectedProjectIds = visibleProjectsOne;480 verify(mockNodeDao).getProjectHeaders(caller.getId(), expectedProjectIds, type, sortColumn, sortDirection, LIMIT_FOR_QUERY, OFFSET);481 }482 483 /**484 * For this case the caller is not an admin, and the caller485 * and the userToGetFor are different. The type is ALL.486 */487 @Test488 public void testGetProjectsMY_PROJECTS(){489 when(userToGetFor.getId()).thenReturn(456L);490 when(userToGetFor.getGroups()).thenReturn(userToGetForGroups);491 492 when(mockAuthorizationManager.getAccessibleProjectIds(anySetOf(Long.class))).thenReturn(493 visibleProjectsOne,494 visibleProjectsTwo495 ); 496 497 type = ProjectListType.ALL;498 // call under test499 ProjectHeaderList results = userProfileManager.getProjects(500 caller, userToGetFor, teamToFetchId, type, sortColumn, sortDirection, nextPageToken);501 assertNotNull(results);502 // Accessible projects should be called once for the userToGetFor and once for the caller.503 verify(mockAuthorizationManager, times(2)).getAccessibleProjectIds(anySetOf(Long.class));504 // the groups for the userToGetFor should exclude public.505 Set<Long> expectedUserToGetGroups = UserProfileManagerImpl.getGroupsMinusPublic(userToGetFor.getGroups());506 verify(mockAuthorizationManager).getAccessibleProjectIds(expectedUserToGetGroups);507 verify(mockAuthorizationManager).getAccessibleProjectIds(caller.getGroups());508 // The projectIds passed to the dao should be the intersection of the caller's projects509 // and the userToGetFor's projects.510 Set<Long> expectedProjectIds = Sets.intersection(visibleProjectsOne, visibleProjectsTwo);511 verify(mockNodeDao).getProjectHeaders(userToGetFor.getId(), expectedProjectIds, type, sortColumn, sortDirection, LIMIT_FOR_QUERY, OFFSET);512 }513 514 /**515 * For this case the caller is not an admin, and the caller516 * and the userToGetFor are different. The type is ALL.517 */518 @Test519 public void testGetProjectsOTHER_USER_PROJECTS(){ 520 when(userToGetFor.getId()).thenReturn(456L);521 when(userToGetFor.getGroups()).thenReturn(userToGetForGroups);522 523 when(mockAuthorizationManager.getAccessibleProjectIds(anySetOf(Long.class))).thenReturn(524 visibleProjectsOne,525 visibleProjectsTwo526 ); 527 528 type = ProjectListType.ALL;529 // call under test530 ProjectHeaderList results = userProfileManager.getProjects(531 caller, userToGetFor, teamToFetchId, type, sortColumn, sortDirection, nextPageToken);532 assertNotNull(results);533 // Accessible projects should be called once for the userToGetFor and once for the caller.534 verify(mockAuthorizationManager, times(2)).getAccessibleProjectIds(anySetOf(Long.class));535 // the groups for the userToGetFor should exclude public.536 Set<Long> expectedUserToGetGroups = UserProfileManagerImpl.getGroupsMinusPublic(userToGetFor.getGroups());537 verify(mockAuthorizationManager).getAccessibleProjectIds(expectedUserToGetGroups);538 verify(mockAuthorizationManager).getAccessibleProjectIds(caller.getGroups());539 // The projectIds passed to the dao should be the intersection of the caller's projects540 // and the userToGetFor's projects.541 Set<Long> expectedProjectIds = Sets.intersection(visibleProjectsOne, visibleProjectsTwo);542 verify(mockNodeDao).getProjectHeaders(userToGetFor.getId(), expectedProjectIds, type, sortColumn, sortDirection, LIMIT_FOR_QUERY, OFFSET);543 }544 545 /**546 * For this case the caller is not an admin, and the caller547 * and the userToGetFor are different. The type is CREATED.548 */549 @Test550 public void testGetProjectsMY_CREATED_PROJECTS(){551 when(userToGetFor.getId()).thenReturn(456L);552 when(userToGetFor.getGroups()).thenReturn(userToGetForGroups);553 554 when(mockAuthorizationManager.getAccessibleProjectIds(anySetOf(Long.class))).thenReturn(555 visibleProjectsOne,556 visibleProjectsTwo557 ); 558 559 type = ProjectListType.CREATED;560 // call under test561 ProjectHeaderList results = userProfileManager.getProjects(562 caller, userToGetFor, teamToFetchId, type, sortColumn, sortDirection, nextPageToken);563 assertNotNull(results);564 // Accessible projects should be called once for the userToGetFor and once for the caller.565 verify(mockAuthorizationManager, times(2)).getAccessibleProjectIds(anySetOf(Long.class));566 // the groups for the userToGetFor should exclude public.567 Set<Long> expectedUserToGetGroups = UserProfileManagerImpl.getGroupsMinusPublic(userToGetFor.getGroups());568 verify(mockAuthorizationManager).getAccessibleProjectIds(expectedUserToGetGroups);569 verify(mockAuthorizationManager).getAccessibleProjectIds(caller.getGroups());570 // The projectIds passed to the dao should be the intersection of the caller's projects571 // and the userToGetFor's projects.572 Set<Long> expectedProjectIds = Sets.intersection(visibleProjectsOne, visibleProjectsTwo);573 verify(mockNodeDao).getProjectHeaders(userToGetFor.getId(), expectedProjectIds, type, sortColumn, sortDirection, LIMIT_FOR_QUERY, OFFSET);574 }575 576 /**577 * For this case the caller is not an admin, and the caller578 * and the userToGetFor are different. The type is PARTICIPATED.579 */580 @Test581 public void testGetProjectsMY_PARTICIPATED_PROJECTS(){ 582 when(userToGetFor.getId()).thenReturn(456L);583 when(userToGetFor.getGroups()).thenReturn(userToGetForGroups);584 585 when(mockAuthorizationManager.getAccessibleProjectIds(anySetOf(Long.class))).thenReturn(586 visibleProjectsOne,587 visibleProjectsTwo588 ); 589 590 type = ProjectListType.PARTICIPATED;591 // call under test592 ProjectHeaderList results = userProfileManager.getProjects(593 caller, userToGetFor, teamToFetchId, type, sortColumn, sortDirection, nextPageToken);594 assertNotNull(results);595 // Accessible projects should be called once for the userToGetFor and once for the caller.596 verify(mockAuthorizationManager, times(2)).getAccessibleProjectIds(anySetOf(Long.class));597 // the groups for the userToGetFor should exclude public.598 Set<Long> expectedUserToGetGroups = UserProfileManagerImpl.getGroupsMinusPublic(userToGetFor.getGroups());599 verify(mockAuthorizationManager).getAccessibleProjectIds(expectedUserToGetGroups);600 verify(mockAuthorizationManager).getAccessibleProjectIds(caller.getGroups());601 // The projectIds passed to the dao should be the intersection of the caller's projects602 // and the userToGetFor's projects.603 Set<Long> expectedProjectIds = Sets.intersection(visibleProjectsOne, visibleProjectsTwo);604 verify(mockNodeDao).getProjectHeaders(userToGetFor.getId(), expectedProjectIds, type, sortColumn, sortDirection, LIMIT_FOR_QUERY, OFFSET);605 }606 607 /**608 * For this case the caller is not an admin, and the caller609 * and the userToGetFor are different. The type is TEAM and610 * we specify one particular tem.611 */612 @Test613 public void testGetProjectsMY_TEAM_PROJECTS(){614 when(userToGetFor.getId()).thenReturn(456L);615 when(userToGetFor.getGroups()).thenReturn(userToGetForGroups);616 617 when(mockAuthorizationManager.getAccessibleProjectIds(anySetOf(Long.class))).thenReturn(618 visibleProjectsOne,619 visibleProjectsTwo620 ); 621 622 teamToFetchId = null;623 type = ProjectListType.TEAM;624 // call under test625 ProjectHeaderList results = userProfileManager.getProjects(626 caller, userToGetFor, teamToFetchId, type, sortColumn, sortDirection, nextPageToken);627 assertNotNull(results);628 // Accessible projects should be called once for the userToGetFor and once for the caller.629 verify(mockAuthorizationManager, times(2)).getAccessibleProjectIds(anySetOf(Long.class));630 // the groups for the userToGetFor should exclude public, and the user631 Set<Long> expectedUserToGetGroups = UserProfileManagerImpl.getGroupsMinusPublicAndSelf(userToGetFor.getGroups(), userToGetFor.getId());632 verify(mockAuthorizationManager).getAccessibleProjectIds(expectedUserToGetGroups);633 verify(mockAuthorizationManager).getAccessibleProjectIds(caller.getGroups());634 // The projectIds passed to the dao should be the intersection of the caller's projects635 // and the userToGetFor's projects.636 Set<Long> expectedProjectIds = Sets.intersection(visibleProjectsOne, visibleProjectsTwo);637 verify(mockNodeDao).getProjectHeaders(userToGetFor.getId(), expectedProjectIds, type, sortColumn, sortDirection, LIMIT_FOR_QUERY, OFFSET);638 }639 640 /**641 * For this case the caller is not an admin, and the caller642 * and the userToGetFor are different. The type is TEAM and643 * we allow all teams.644 */645 @Test 646 public void testGetProjectsTEAM_PROJECTS(){647 when(userToGetFor.getId()).thenReturn(456L);648 when(userToGetFor.getGroups()).thenReturn(userToGetForGroups);649 650 when(mockAuthorizationManager.getAccessibleProjectIds(anySetOf(Long.class))).thenReturn(651 visibleProjectsOne,652 visibleProjectsTwo653 ); 654 655 teamToFetchId = 999L;656 userToGetFor.getGroups().add(teamToFetchId);657 type = ProjectListType.TEAM;658 // call under test659 ProjectHeaderList results = userProfileManager.getProjects(660 caller, userToGetFor, teamToFetchId, type, sortColumn, sortDirection, nextPageToken);661 assertNotNull(results);662 // Accessible projects should be called once for the userToGetFor and once for the caller.663 verify(mockAuthorizationManager, times(2)).getAccessibleProjectIds(anySetOf(Long.class));664 // the groups for the userToGetFor should exclude public, and the user665 Set<Long> expectedUserToGetGroups = Sets.newHashSet(teamToFetchId);666 verify(mockAuthorizationManager).getAccessibleProjectIds(expectedUserToGetGroups);667 verify(mockAuthorizationManager).getAccessibleProjectIds(caller.getGroups());668 // The projectIds passed to the dao should be the intersection of the caller's projects669 // and the userToGetFor's projects.670 Set<Long> expectedProjectIds = Sets.intersection(visibleProjectsOne, visibleProjectsTwo);671 verify(mockNodeDao).getProjectHeaders(userToGetFor.getId(), expectedProjectIds, type, sortColumn, sortDirection, LIMIT_FOR_QUERY, OFFSET);672 }673 674 @Test675 public void testGetProjectsNonTeamWithTeamId() { 676 teamToFetchId = 999L;677 type = ProjectListType.ALL;678 try {679 userProfileManager.getProjects(680 caller, userToGetFor, teamToFetchId, type, sortColumn, sortDirection, nextPageToken);681 fail("IllegalArgumentException expected");682 } catch (IllegalArgumentException e) {683 // as expected684 }685 686 }687 688 /**689 * Must be able to call getProjects() for each type.690 */691 @Test 692 public void testGetProjectsAllTypes(){693 when(userToGetFor.getId()).thenReturn(456L);694 when(userToGetFor.getGroups()).thenReturn(userToGetForGroups);695 696 when(mockAuthorizationManager.getAccessibleProjectIds(anySetOf(Long.class))).thenReturn(697 visibleProjectsOne,698 visibleProjectsTwo699 ); 700 701 userToGetFor.getGroups().add(teamToFetchId);702 for(ProjectListType type: ProjectListType.values()) {703 ProjectHeaderList results = userProfileManager.getProjects(704 caller, userToGetFor, teamToFetchId, type, sortColumn, sortDirection, nextPageToken);705 assertNotNull(results);706 }707 }708 709 @Test710 public void testGetUserProfileImageUrl() {...
Source:EntityHierarchyChangeWorkerUnitTest.java
...4import static org.junit.Assert.assertNotNull;5import static org.mockito.ArgumentMatchers.any;6import static org.mockito.ArgumentMatchers.anyListOf;7import static org.mockito.ArgumentMatchers.anyLong;8import static org.mockito.ArgumentMatchers.anySetOf;9import static org.mockito.ArgumentMatchers.anyString;10import static org.mockito.ArgumentMatchers.eq;11import static org.mockito.Mockito.times;12import static org.mockito.Mockito.verify;13import static org.mockito.Mockito.verifyNoMoreInteractions;14import static org.mockito.Mockito.when;1516import java.util.Date;17import java.util.LinkedList;18import java.util.List;1920import org.junit.Before;21import org.junit.Test;22import org.mockito.ArgumentCaptor;23import org.mockito.Captor;24import org.mockito.Mock;25import org.mockito.MockitoAnnotations;26import org.sagebionetworks.common.util.progress.ProgressCallback;27import org.sagebionetworks.repo.manager.message.RepositoryMessagePublisher;28import org.sagebionetworks.repo.model.EntityType;29import org.sagebionetworks.repo.model.NodeDAO;30import org.sagebionetworks.repo.model.NodeIdAndType;31import org.sagebionetworks.repo.model.ObjectType;32import org.sagebionetworks.repo.model.dbo.dao.DBOChangeDAO;33import org.sagebionetworks.repo.model.message.ChangeMessage;34import org.sagebionetworks.repo.model.message.ChangeType;35import org.sagebionetworks.util.Clock;36import org.sagebionetworks.worker.entity.EntityHierarchyChangeWorker;37import org.sagebionetworks.workers.util.aws.message.RecoverableMessageException;38import org.springframework.test.util.ReflectionTestUtils;3940import com.google.common.collect.Lists;41import com.google.common.collect.Sets;4243public class EntityHierarchyChangeWorkerUnitTest {4445 @Mock46 DBOChangeDAO mockChangeDao;47 @Mock48 NodeDAO mockNodeDao;49 @Mock50 RepositoryMessagePublisher mockMessagePublisher;51 @Mock52 Clock mockClock;53 @Mock54 ProgressCallback mockProgressCallback;55 @Captor 56 private ArgumentCaptor<List<ChangeMessage>> publishCapture;57 58 EntityHierarchyChangeWorker worker;59 ChangeMessage message;60 String parentId;61 String folderId;62 List<NodeIdAndType> filesOnly;63 List<NodeIdAndType> empty;64 List<NodeIdAndType> filesAndFolders;65 List<ChangeMessage> chagnes;66 67 @Before68 public void before(){69 MockitoAnnotations.initMocks(this);70 worker = new EntityHierarchyChangeWorker();71 ReflectionTestUtils.setField(worker, "changeDao", mockChangeDao);72 ReflectionTestUtils.setField(worker, "nodeDao", mockNodeDao);73 ReflectionTestUtils.setField(worker, "messagePublisher", mockMessagePublisher);74 ReflectionTestUtils.setField(worker, "clock", mockClock);75 76 message = new ChangeMessage();77 message.setTimestamp(new Date(1));78 message.setChangeType(ChangeType.UPDATE);79 message.setObjectId("syn123");80 81 when(mockClock.currentTimeMillis()).thenReturn(1L, 2L,3L,4L,5L);82 83 parentId = "syn123";84 folderId = "syn444";85 86 filesOnly = Lists.newArrayList(87 new NodeIdAndType("syn111", EntityType.file),88 new NodeIdAndType("syn222", EntityType.file)89 );90 empty = new LinkedList<>();91 filesAndFolders = Lists.newArrayList(92 new NodeIdAndType("syn333", EntityType.file),93 new NodeIdAndType(folderId, EntityType.folder)94 );95 96 ChangeMessage childChange = new ChangeMessage();97 childChange.setObjectId("syn123");98 }99 100 @Test101 public void testOldMessage() throws RecoverableMessageException, Exception{102 // set the time past the first message103 when(mockClock.currentTimeMillis()).thenReturn(104 EntityHierarchyChangeWorker.MAX_MESSAGE_AGE_MS105 + message.getTimestamp().getTime() + 1);106 // call under test107 worker.run(mockProgressCallback, message);108 // the message should be ignored.109 verifyNoMoreInteractions(110 mockProgressCallback111 ,mockChangeDao112 ,mockNodeDao113 ,mockMessagePublisher114 );115 }116 117 @Test118 public void testNewMessage() throws RecoverableMessageException, Exception{119 // call under test120 worker.run(mockProgressCallback, message);121 verify(mockNodeDao).getChildren(eq(message.getObjectId()), anyLong(), anyLong());122 }123 124 @Test125 public void testRecursiveBroadcastMessagesWithoutRecursion() throws InterruptedException{126 // setup only files in this container.127 when(mockNodeDao.getChildren(anyString(), anyLong(), anyLong())).thenReturn(filesOnly, empty);128 // call under test129 worker.recursiveBroadcastMessages(mockProgressCallback, parentId, ChangeType.CREATE);130 verify(mockNodeDao, times(2)).getChildren(anyString(), anyLong(), anyLong());131 verify(mockChangeDao).getChangesForObjectIds(ObjectType.ENTITY, Sets.newHashSet(111L,222L));132 verify(mockMessagePublisher).publishBatchToTopic(any(ObjectType.class), anyListOf(ChangeMessage.class));133 verify(mockClock, times(1)).sleep(anyLong());134 }135 136 @Test137 public void testRecursiveBroadcastMessagesWithRecursion() throws InterruptedException{138 // setup files and folders for children139 when(mockNodeDao.getChildren(anyString(), anyLong(), anyLong())).thenReturn(filesAndFolders,empty, filesOnly, empty);140 // call under test141 worker.recursiveBroadcastMessages(mockProgressCallback, parentId, ChangeType.CREATE);142 // should be called twice with the original parent143 verify(mockNodeDao, times(2)).getChildren(eq(parentId), anyLong(), anyLong());144 // should be called twice for the child folder145 verify(mockNodeDao, times(2)).getChildren(eq(folderId), anyLong(), anyLong());146 verify(mockChangeDao).getChangesForObjectIds(ObjectType.ENTITY, Sets.newHashSet(111L,222L));147 verify(mockMessagePublisher, times(2)).publishBatchToTopic(any(ObjectType.class), anyListOf(ChangeMessage.class));148 verify(mockClock, times(2)).sleep(anyLong());149 }150 151 @Test152 public void testRecursiveBroadcastMessagesMultiplePages() throws InterruptedException{153 // setup multiple pages of files154 when(mockNodeDao.getChildren(anyString(), anyLong(), anyLong())).thenReturn(filesOnly, filesOnly, empty);155 // call under test156 worker.recursiveBroadcastMessages(mockProgressCallback, parentId, ChangeType.CREATE);157 // should be called three time with the original parent158 verify(mockNodeDao, times(3)).getChildren(eq(parentId), anyLong(), anyLong());159 verify(mockChangeDao, times(2)).getChangesForObjectIds(ObjectType.ENTITY, Sets.newHashSet(111L,222L));160 verify(mockMessagePublisher, times(2)).publishBatchToTopic(any(ObjectType.class), anyListOf(ChangeMessage.class));161 verify(mockClock, times(2)).sleep(anyLong());162 }163 164 /**165 * Test for PLFM-1723.166 * 167 * @throws InterruptedException168 */169 @Test170 public void testRecursiveBroadcastMessagesChangeType() throws InterruptedException{171 ChangeMessage currentMessage = new ChangeMessage();172 currentMessage.setChangeType(ChangeType.UPDATE);173 when(mockChangeDao.getChangesForObjectIds(any(ObjectType.class), anySetOf(Long.class))).thenReturn(Lists.newArrayList(currentMessage));174 175 // setup multiple pages of files176 when(mockNodeDao.getChildren(anyString(), anyLong(), anyLong())).thenReturn(filesOnly, empty);177 // call under test178 worker.recursiveBroadcastMessages(mockProgressCallback, parentId, ChangeType.DELETE);179180 verify(mockMessagePublisher, times(1)).publishBatchToTopic(any(ObjectType.class), publishCapture.capture());181 List<ChangeMessage> published = publishCapture.getValue();182 assertNotNull(published);183 assertEquals(1, published.size());184 ChangeMessage publishedMessage = published.get(0);185 // the original message was a create but the pushed message should be a delete.186 assertEquals(ChangeType.DELETE, publishedMessage.getChangeType());187 }
...
Source:RuleNameServiceImplTest.java
...31import org.mockito.junit.MockitoJUnitRunner;32import org.uberfire.backend.vfs.Path;33import static org.junit.Assert.*;34import static org.mockito.ArgumentMatchers.any;35import static org.mockito.ArgumentMatchers.anySetOf;36import static org.mockito.ArgumentMatchers.eq;37import static org.mockito.Mockito.*;38@RunWith(MockitoJUnitRunner.class)39public class RuleNameServiceImplTest {40 private static final String PROJECT_ROOT_URI = "project-root-uri";41 @Mock42 private RefactoringQueryService queryService;43 @Mock44 private KieModuleService projectService;45 @Mock46 private Path path;47 @Mock48 private Path projectRootPath;49 @Mock50 private KieModule module;51 private RuleNameServiceImpl service;52 @Before53 public void setup() {54 this.service = new RuleNameServiceImpl(queryService,55 projectService);56 when(projectService.resolveModule(any(Path.class))).thenReturn(module);57 when(module.getRootPath()).thenReturn(projectRootPath);58 when(projectRootPath.toURI()).thenReturn(PROJECT_ROOT_URI);59 when(queryService.query(eq(FindRulesByModuleQuery.NAME),60 anySetOf(ValueIndexTerm.class))).thenReturn(getResults());61 }62 private List<RefactoringPageRow> getResults() {63 final List<RefactoringPageRow> results = new ArrayList<>();64 results.add(new RefactoringRuleNamePageRow() {{65 setValue(new RuleName("rule1",66 "org.kie.test.package"));67 }});68 results.add(new RefactoringRuleNamePageRow() {{69 setValue(new RuleName("rule2",70 "org.kie.test.package"));71 }});72 return results;73 }74 @Test...
Source:AliasLoaderTest.java
...26import org.junit.Test;27import org.junit.runner.RunWith;28import org.mockito.Mock;29import org.mockito.runners.MockitoJUnitRunner;30import static org.mockito.ArgumentMatchers.anySetOf;31import static org.mockito.Mockito.never;32import static org.mockito.Mockito.verify;33import static org.mockito.Mockito.when;34@RunWith(MockitoJUnitRunner.class)35public class AliasLoaderTest {36 @Mock private AliasManager aliasManager;37 @Mock private AliasStore aliasStore;38 @Mock private Alias alias1;39 @Mock private Alias alias2;40 @Mock private Alias alias3;41 private Set<Alias> aliases;42 private AliasLoader loader;43 @Before44 public void setup() {45 loader = new AliasLoader(aliasManager, aliasStore);46 aliases = Sets.newHashSet(alias1, alias2, alias3);47 }48 @Test49 public void testLoadPreservesDirtyState() {50 when(aliasManager.isDirty()).thenReturn(true);51 when(aliasStore.readAliases()).thenReturn(aliases);52 loader.load();53 verify(aliasManager).setDirty(true);54 }55 @Test56 public void testLoadAddsEachAlias() {57 when(aliasStore.readAliases()).thenReturn(aliases);58 loader.load();59 verify(aliasManager).addAlias(alias1);60 verify(aliasManager).addAlias(alias2);61 verify(aliasManager).addAlias(alias3);62 }63 @Test64 public void testSaveDoesNotWriteIfManagerNotDirty() {65 when(aliasManager.isDirty()).thenReturn(false);66 loader.save();67 verify(aliasStore, never()).writeAliases(anySetOf(Alias.class));68 }69 @Test70 public void testSaveSetsDirtyToFalse() {71 when(aliasManager.isDirty()).thenReturn(true);72 when(aliasManager.getAliases()).thenReturn(aliases);73 loader.save();74 verify(aliasManager).setDirty(false);75 }76 @Test77 public void testSaveSavesAliases() {78 when(aliasManager.isDirty()).thenReturn(true);79 when(aliasManager.getAliases()).thenReturn(aliases);80 loader.save();81 verify(aliasStore).writeAliases(aliases);...
Source:ExecuteCommandPresenterTest.java
...8 * Contributors:9 * Red Hat, Inc. - initial API and implementation10 */11package org.eclipse.che.ide.command.toolbar.commands;12import static org.mockito.ArgumentMatchers.anySetOf;13import static org.mockito.ArgumentMatchers.eq;14import static org.mockito.Mockito.mock;15import static org.mockito.Mockito.verify;16import static org.mockito.Mockito.when;17import com.google.gwt.user.client.ui.AcceptsOneWidget;18import com.google.inject.Provider;19import com.google.web.bindery.event.shared.EventBus;20import org.eclipse.che.ide.api.command.CommandExecutor;21import org.eclipse.che.ide.api.command.CommandGoal;22import org.eclipse.che.ide.api.command.CommandImpl;23import org.eclipse.che.ide.api.command.CommandManager;24import org.eclipse.che.ide.api.workspace.model.MachineImpl;25import org.eclipse.che.ide.command.goal.DebugGoal;26import org.eclipse.che.ide.command.goal.RunGoal;27import org.eclipse.che.ide.command.toolbar.CommandCreationGuide;28import org.junit.Before;29import org.junit.Test;30import org.junit.runner.RunWith;31import org.mockito.InjectMocks;32import org.mockito.Mock;33import org.mockito.junit.MockitoJUnitRunner;34/** Tests for {@link ExecuteCommandPresenter}. */35@RunWith(MockitoJUnitRunner.class)36public class ExecuteCommandPresenterTest {37 @Mock private ExecuteCommandView view;38 @Mock private CommandManager commandManager;39 @Mock private Provider<CommandExecutor> commandExecutorProvider;40 @Mock private CommandCreationGuide commandCreationGuide;41 @Mock private RunGoal runGoal;42 @Mock private DebugGoal debugGoal;43 @Mock private EventBus eventBus;44 @InjectMocks private ExecuteCommandPresenter presenter;45 @Mock private CommandExecutor commandExecutor;46 @Before47 public void setUp() {48 when(commandExecutorProvider.get()).thenReturn(commandExecutor);49 }50 @Test51 public void shouldSetDelegate() throws Exception {52 verify(view).setDelegate(presenter);53 }54 @Test55 public void testGo() throws Exception {56 AcceptsOneWidget container = mock(AcceptsOneWidget.class);57 presenter.go(container);58 verify(view).setGoals(anySetOf(CommandGoal.class));59 verify(container).setWidget(view);60 }61 @Test62 public void shouldExecuteCommand() throws Exception {63 CommandImpl command = mock(CommandImpl.class);64 presenter.onCommandExecute(command);65 verify(commandExecutor).executeCommand(eq(command));66 }67 @Test68 public void shouldExecuteCommandOnMachine() throws Exception {69 CommandImpl command = mock(CommandImpl.class);70 MachineImpl machine = mock(MachineImpl.class);71 when(machine.getName()).thenReturn("machine_name");72 presenter.onCommandExecute(command, machine);...
Source:AnyXMatchersAcceptNullsTest.java
...27 Mockito.when(mock.oneArg(ArgumentMatchers.anyString())).thenReturn("0");28 Mockito.when(mock.forList(ArgumentMatchers.anyListOf(String.class))).thenReturn("1");29 Mockito.when(mock.forMap(ArgumentMatchers.anyMapOf(String.class, String.class))).thenReturn("2");30 Mockito.when(mock.forCollection(ArgumentMatchers.anyCollectionOf(String.class))).thenReturn("3");31 Mockito.when(mock.forSet(ArgumentMatchers.anySetOf(String.class))).thenReturn("4");32 Assert.assertEquals(null, mock.oneArg(((Object) (null))));33 Assert.assertEquals(null, mock.oneArg(((String) (null))));34 Assert.assertEquals(null, mock.forList(null));35 Assert.assertEquals(null, mock.forMap(null));36 Assert.assertEquals(null, mock.forCollection(null));37 Assert.assertEquals(null, mock.forSet(null));38 }39 @Test40 public void shouldNotAcceptNullInAllAnyPrimitiveWrapperMatchers() {41 Mockito.when(mock.forInteger(ArgumentMatchers.anyInt())).thenReturn("0");42 Mockito.when(mock.forCharacter(ArgumentMatchers.anyChar())).thenReturn("1");43 Mockito.when(mock.forShort(ArgumentMatchers.anyShort())).thenReturn("2");44 Mockito.when(mock.forByte(ArgumentMatchers.anyByte())).thenReturn("3");45 Mockito.when(mock.forBoolean(ArgumentMatchers.anyBoolean())).thenReturn("4");...
Source:NewMatchersTest.java
...37 Mockito.verify(mock, Mockito.times(1)).forMap(ArgumentMatchers.anyMapOf(String.class, String.class));38 }39 @Test40 public void shouldAllowAnySet() {41 Mockito.when(mock.forSet(ArgumentMatchers.anySetOf(String.class))).thenReturn("matched");42 Assert.assertEquals("matched", mock.forSet(new HashSet<String>()));43 Assert.assertEquals(null, mock.forSet(null));44 Mockito.verify(mock, Mockito.times(1)).forSet(ArgumentMatchers.anySetOf(String.class));45 }46 @Test47 public void shouldAllowAnyIterable() {48 Mockito.when(mock.forIterable(ArgumentMatchers.anyIterableOf(String.class))).thenReturn("matched");49 Assert.assertEquals("matched", mock.forIterable(new HashSet<String>()));50 Assert.assertEquals(null, mock.forIterable(null));51 Mockito.verify(mock, Mockito.times(1)).forIterable(ArgumentMatchers.anyIterableOf(String.class));52 }53}...
Source:VisitSDJpaServiceTest.java
1package guru.springframework.sfgpetclinic.services.springdatajpa;2import static org.assertj.core.api.Assertions.assertThat;3import static org.mockito.ArgumentMatchers.anyLong;4import static org.mockito.ArgumentMatchers.any;5//import static org.mockito.ArgumentMatchers.anySetOf;6import static org.mockito.Mockito.verify;7import static org.mockito.Mockito.when;8import java.util.HashSet;9import java.util.Optional;10import java.util.Set;11import org.junit.jupiter.api.DisplayName;12import org.junit.jupiter.api.Test;13import org.junit.jupiter.api.extension.ExtendWith;14import org.mockito.InjectMocks;15import org.mockito.Mock;16import org.mockito.junit.jupiter.MockitoExtension;17import guru.springframework.sfgpetclinic.model.Visit;18import guru.springframework.sfgpetclinic.repositories.VisitRepository;19@ExtendWith(MockitoExtension.class)...
anySetOf
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anySetOf;2import static org.mockito.ArgumentMatchers.anyString;3import static org.mockito.Mockito.mock;4import static org.mockito.Mockito.verify;5import static org.mockito.Mockito.when;6import java.util.HashSet;7import java.util.Set;8import org.junit.Test;9import org.mockito.ArgumentCaptor;10public class MockitoTest {11 public void test() {12 Set<String> set = new HashSet<>();13 set.add("one");14 set.add("two");15 set.add("three");16 set.add("four");17 Set<String> mockSet = mock(Set.class);18 when(mockSet.containsAll(anySetOf(String.class))).thenReturn(true);19 mockSet.containsAll(set);20 ArgumentCaptor<Set> captor = ArgumentCaptor.forClass(Set.class);21 verify(mockSet).containsAll(captor.capture());22 System.out.println(captor.getValue());23 }24}
anySetOf
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anySetOf;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.verify;4import java.util.HashSet;5import java.util.Set;6public class MockitoAnySetOfExample {7 public static void main(String[] args) {8 Set mock = mock(Set.class);9 mock.addAll(anySetOf(Integer.class));10 System.out.println(mock.addAll(new HashSet<Integer>()));11 System.out.println(mock.addAll(new HashSet<String>()));12 verify(mock).addAll(anySetOf(Integer.class));13 }14}15Mockito ArgumentCaptor Mockito anyString() method16Mockito anyString() method Mockito anyInt() method17Mockito anyInt() method Mockito anyList() method18Mockito anyList() method Mockito anyMap() method19Mockito anyMap() method Mockito anyCollection() method20Mockito anyCollection() method Mockito anyIterable() method21Mockito anyIterable() method Mockito any() method22Mockito any() method Mockito anyObject() method23Mockito anyObject() method Mockito anyVararg() method24Mockito anyVararg() method Mockito anyBoolean() method25Mockito anyBoolean() method Mockito anyByte() method26Mockito anyByte() method Mockito anyChar() method27Mockito anyChar() method Mockito anyDouble() method28Mockito anyDouble() method Mockito anyFloat() method29Mockito anyFloat() method Mockito anyLo
anySetOf
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anySetOf;2import static org.mockito.Mockito.when;3import static org.mockito.MockitoAnnotations.initMocks;4import java.util.HashSet;5import java.util.Set;6import org.junit.Before;7import org.junit.Test;8import org.mockito.InjectMocks;9import org.mockito.Mock;10import org.mockito.Mockito;11import org.mockito.Spy;12{13 private Set<String> mockSet;14 private Set<String> spySet = new HashSet<>();15 private Set<String> injectSet = new HashSet<>();16 public void setup()17 {18 initMocks(this);19 }20 public void testMockSet()21 {22 when(mockSet.contains(anySetOf(String.class))).thenReturn(true);23 System.out.println(mockSet.contains("A"));24 System.out.println(mockSet.contains("B"));25 System.out.println(mockSet.contains("C"));26 }27 public void testSpySet()28 {29 when(spySet.contains(anySetOf(String.class))).thenReturn(true);30 System.out.println(spySet.contains("A"));31 System.out.println(spySet.contains("B"));32 System.out.println(spySet.contains("C"));33 }34 public void testInjectSet()35 {36 when(injectSet.contains(anySetOf(String.class))).thenReturn(true);37 System.out.println(injectSet.contains("A"));38 System.out.println(injectSet.contains("B"));39 System.out.println(injectSet.contains("C"));40 }41}
anySetOf
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anySetOf;2import static org.mockito.Mockito.doNothing;3import static org.mockito.Mockito.mock;4import static org.mockito.Mockito.verify;5import java.util.HashSet;6import java.util.Set;7public class MockitoTest {8 public static void main(String[] args) {9 Set mockSet = mock(HashSet.class);10 Set set = new HashSet();11 set.add("1");12 set.add("2");13 doNothing().when(mockSet).addAll(anySetOf(HashSet.class));14 mockSet.addAll(set);15 verify(mockSet).addAll(anySetOf(HashSet.class));16 }17}18java.lang.AssertionError: Argument(s) are different! Wanted:19set.addAll(20 anySetOf(HashSet.class)21);22-> at org.mockito.Mockito.verify(Mockito.java:180)23set.addAll(24);25-> at MockitoTest.main(MockitoTest.java:29)
anySetOf
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3import java.util.HashSet;4import java.util.Set;5public class AnySetOf {6 public static void main(String[] args) {7 Set<Integer> set = new HashSet<Integer>();8 set.add(1);9 set.add(2);10 set.add(3);11 Set<Integer> set1 = new HashSet<Integer>();12 set1.add(1);13 set1.add(2);14 set1.add(3);15 Set<Integer> set2 = new HashSet<Integer>();16 set2.add(4);17 set2.add(5);18 set2.add(6);19 Set<Integer> set3 = new HashSet<Integer>();20 set3.add(4);21 set3.add(5);22 set3.add(6);23 Set<Integer> set4 = new HashSet<Integer>();24 set4.add(7);25 set4.add(8);26 set4.add(9);27 Set<Integer> set5 = new HashSet<Integer>();28 set5.add(7);29 set5.add(8);30 set5.add(9);31 Set<Integer> set6 = new HashSet<Integer>();32 set6.add(10);33 set6.add(11);34 set6.add(12);35 Set<Integer> set7 = new HashSet<Integer>();36 set7.add(10);37 set7.add(11);38 set7.add(12);39 Set<Integer> set8 = new HashSet<Integer>();40 set8.add(13);41 set8.add(14);42 set8.add(15);43 Set<Integer> set9 = new HashSet<Integer>();44 set9.add(13);45 set9.add(14);46 set9.add(15);47 Set<Integer> set10 = new HashSet<Integer>();48 set10.add(16);49 set10.add(17);50 set10.add(18);51 Set<Integer> set11 = new HashSet<Integer>();52 set11.add(16);53 set11.add(17);54 set11.add(18);55 Set<Integer> set12 = new HashSet<Integer>();56 set12.add(19);57 set12.add(20);58 set12.add(21);59 Set<Integer> set13 = new HashSet<Integer>();60 set13.add(19);61 set13.add(20);62 set13.add(21);63 Set<Integer> set14 = new HashSet<Integer>();64 set14.add(22
anySetOf
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3import java.util.List;4import java.util.Set;5public class MockingAnySetOf {6 public static void main(String[] args) {7 List<String> list = Mockito.mock(List.class);8 Set<String> set = Set.of("one", "two", "three");9 Mockito.when(list.addAll(ArgumentMatchers.anySetOf(String.class))).thenReturn(true);10 list.addAll(set);11 Mockito.verify(list).addAll(set);12 }13}14import org.mockito.ArgumentMatchers;15import org.mockito.Mockito;16import java.util.List;17import java.util.Set;18public class MockingAnySetOf {19 public static void main(String[] args) {20 List<String> list = Mockito.mock(List.class);21 Set<String> set = Set.of("one", "two", "three");22 Mockito.when(list.addAll(ArgumentMatchers.anySetOf(String.class))).thenReturn(true);23 list.addAll(set);24 Mockito.verify(list).addAll(set);25 }26}27Related Posts: Mockito Argument Matcher anySetOf() Method28Mockito Argument Matcher anyCollectionOf() Method29Mockito Argument Matcher anyMapOf() Method30Mockito Argument Matcher anyListOf() Method31Mockito Argument Matcher anyIterableOf() Method32Mockito Argument Matcher any() Method33Mockito Argument Matcher anyInt() Method34Mockito Argument Matcher anyLong() Method35Mockito Argument Matcher anyFloat() Method36Mockito Argument Matcher anyDouble() Method37Mockito Argument Matcher anyBoolean() Method38Mockito Argument Matcher anyByte() Method39Mockito Argument Matcher anyChar() Method40Mockito Argument Matcher anyShort() Method41Mockito Argument Matcher anyString() Method42Mockito Argument Matcher anyObject() Method43Mockito Argument Matcher anyVararg() Method44Mockito Argument Matcher anyList() Method45Mockito Argument Matcher anySet() Method46Mockito Argument Matcher anyCollection() Method47Mockito Argument Matcher anyMap() Method48Mockito Argument Matcher anyIterable() Method49Mockito Argument Matcher anyArray() Method50Mockito Argument Matcher anyArray(Class) Method51Mockito Argument Matcher anyList(Class) Method52Mockito Argument Matcher anySet(Class)
anySetOf
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3import java.util.HashSet;4import java.util.Set;5public class MockitoAnySetOfTest {6 public static void main(String[] args) {7 Set<String> mockSet = Mockito.mock(Set.class);8 Mockito.when(mockSet.size())9 .thenReturn(5);10 Mockito.when(mockSet.contains(ArgumentMatchers.anySetOf(String.class)))11 .thenReturn(true);12 System.out.println(mockSet.contains(new HashSet<String>()));13 Mockito.verify(mockSet).contains(ArgumentMatchers.anySetOf(String.class));14 }15}16Mockito ArgumentCaptor.capture()17Mockito ArgumentCaptor.capture() Examples18Mockito ArgumentCaptor.capture() Example 119Mockito ArgumentCaptor.capture() Example 220Mockito ArgumentCaptor.capture() Example 321Mockito ArgumentCaptor.capture() Example 422Mockito ArgumentCaptor.capture() Example 523Mockito ArgumentCaptor.capture() Example 624Mockito ArgumentCaptor.capture() Example 725Mockito ArgumentCaptor.capture() Example 826Mockito ArgumentCaptor.capture() Example 927Mockito ArgumentCaptor.capture() Example 1028Mockito ArgumentCaptor.capture() Example 1129Mockito ArgumentCaptor.capture() Example 1230Mockito ArgumentCaptor.capture() Example 1331Mockito ArgumentCaptor.capture() Example 1432Mockito ArgumentCaptor.capture() Example 1533Mockito ArgumentCaptor.capture() Example 1634Mockito ArgumentCaptor.capture() Example 1735Mockito ArgumentCaptor.capture() Example 1836Mockito ArgumentCaptor.capture() Example 1937Mockito ArgumentCaptor.capture() Example 2038Mockito ArgumentCaptor.capture() Example 2139Mockito ArgumentCaptor.capture() Example 22
anySetOf
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anySetOf;2import static org.mockito.ArgumentMatchers.anyString;3import static org.mockito.Mockito.mock;4import static org.mockito.Mockito.when;5import java.util.HashSet;6import java.util.Set;7public class AnySetOfExample {8 public static void main(String[] args) {9 Set<String> set = new HashSet<>();10 set.add("test");11 set.add("test1");12 set.add("test2");13 set.add("test3");14 set.add("test4");15 set.add("test5");16 set.add("test6");17 set.add("test7");18 set.add("test8");19 set.add("test9");20 set.add("test10");21 set.add("test11");22 set.add("test12");23 set.add("test13");24 set.add("test14");25 set.add("test15");26 set.add("test16");27 set.add("test17");28 set.add("test18");29 set.add("test19");30 set.add("test20");31 set.add("test21");32 set.add("test22");33 set.add("test23");34 set.add("test24");35 set.add("test25");36 set.add("test26");37 set.add("test27");38 set.add("test28");39 set.add("test29");40 set.add("test30");41 set.add("test31");42 set.add("test32");43 set.add("test33");44 set.add("test34");45 set.add("test35");46 set.add("test36");47 set.add("test37");48 set.add("test38");49 set.add("test39");50 set.add("test40");51 set.add("test41");52 set.add("test42");53 set.add("test43");54 set.add("test44");55 set.add("test45");56 set.add("test46");57 set.add("test47");58 set.add("test48");59 set.add("test49");60 set.add("test50");61 set.add("test51");62 set.add("test52");63 set.add("test53");64 set.add("test54");65 set.add("test55");66 set.add("test56");67 set.add("test57");68 set.add("test58");69 set.add("
anySetOf
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anySetOf;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.verify;4import java.util.Set;5public class MockitoAnySetOfDemo {6 public static void main(String[] args) {7 Set<String> set = mock(Set.class);8 set.add("A");9 set.add("B");10 set.add("C");11 verify(set).addAll(anySetOf(String.class));12 System.out.println("MockitoAnySetOfDemo.main() called");13 }14}15MockitoAnySetOfDemo.main() called
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!!