Skip to content

Commit

Permalink
feat[DonationRepository]: Add filterByUser() method and respective JU…
Browse files Browse the repository at this point in the history
…nit test for it
  • Loading branch information
Fredrik Marjoni committed Mar 7, 2026
1 parent c3b7e40 commit a875a55
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,9 @@ public HashMap<Integer, Donation> sortByAmount() {

/**
* Returns all donations associated with a specific organization.
*
* @param orgNumber the organization ID to filter by
* @return a map containing all donations that belong to the given organization
* @throws IllegalArgumentException if the orgNumber is not positive
*/
public HashMap<Integer, Donation> filterByOrganization(int orgNumber) {
if (orgNumber <= 0) {
Expand All @@ -172,4 +172,24 @@ public HashMap<Integer, Donation> filterByOrganization(int orgNumber) {
LinkedHashMap::new
));
}

/**
* Returns all donations made by a specific user.
* @param userId the user ID to filter by
* @return a map containing all donations that belong to the given user
* @throws IllegalArgumentException if the userId is not positive
*/
public HashMap<Integer, Donation> filterByUser(int userId) {
if (userId <= 0) {
throw new IllegalArgumentException("User ID must be positive");
}
return content.entrySet().stream()
.filter(entry -> entry.getValue().userId() == userId)
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -239,4 +239,28 @@ void filterByOrganizationHandlesDuplicateKeysWithLambda() {
Map<Integer, Donation> filtered = repo.filterByOrganization(201);
assertEquals(d1, filtered.get(1));
}

@Test
void filterByUserIdMatches() {
repo.addDonation(donation1);
repo.addDonation(donation3);

Map<Integer, Donation> filtered = repo.filterByUser(102);
assertEquals(1, filtered.size());
assertTrue(filtered.containsKey(1));
}

@Test
void filterByUserIdNoMatch() {
repo.addDonation(donation1);
Map<Integer, Donation> filtered = repo.filterByUser(999);
assertTrue(filtered.isEmpty());
}

@Test
void filterByUserIdThrowsIfNegative() {
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
() -> repo.filterByUser(0));
assertEquals("User ID must be positive", ex.getMessage());
}
}

0 comments on commit a875a55

Please sign in to comment.