From a875a553041d212434031f4f142235a91bed1790 Mon Sep 17 00:00:00 2001 From: Fredrik Marjoni Date: Sat, 7 Mar 2026 19:06:00 +0100 Subject: [PATCH] feat[DonationRepository]: Add filterByUser() method and respective JUnit test for it --- .../model/donation/DonationRepository.java | 22 ++++++++++++++++- .../donation/DonationRepositoryTest.java | 24 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/main/java/edu/group5/app/model/donation/DonationRepository.java b/src/main/java/edu/group5/app/model/donation/DonationRepository.java index 54845a5..8f9b4ec 100644 --- a/src/main/java/edu/group5/app/model/donation/DonationRepository.java +++ b/src/main/java/edu/group5/app/model/donation/DonationRepository.java @@ -154,9 +154,9 @@ public HashMap 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 filterByOrganization(int orgNumber) { if (orgNumber <= 0) { @@ -172,4 +172,24 @@ public HashMap 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 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 + )); + } } diff --git a/src/test/java/edu/group5/app/model/donation/DonationRepositoryTest.java b/src/test/java/edu/group5/app/model/donation/DonationRepositoryTest.java index 04d4626..fd7ec1e 100644 --- a/src/test/java/edu/group5/app/model/donation/DonationRepositoryTest.java +++ b/src/test/java/edu/group5/app/model/donation/DonationRepositoryTest.java @@ -239,4 +239,28 @@ void filterByOrganizationHandlesDuplicateKeysWithLambda() { Map filtered = repo.filterByOrganization(201); assertEquals(d1, filtered.get(1)); } + + @Test + void filterByUserIdMatches() { + repo.addDonation(donation1); + repo.addDonation(donation3); + + Map filtered = repo.filterByUser(102); + assertEquals(1, filtered.size()); + assertTrue(filtered.containsKey(1)); + } + + @Test + void filterByUserIdNoMatch() { + repo.addDonation(donation1); + Map 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()); + } } \ No newline at end of file