diff --git a/src/main/java/com/example/bankapp/controller/BankController.java b/src/main/java/com/example/bankapp/controller/BankController.java index 19fcded7..62724436 100644 --- a/src/main/java/com/example/bankapp/controller/BankController.java +++ b/src/main/java/com/example/bankapp/controller/BankController.java @@ -48,10 +48,18 @@ public String login() { } @PostMapping("/deposit") - public String deposit(@RequestParam BigDecimal amount) { + public String deposit(@RequestParam BigDecimal amount, Model model) { String username = SecurityContextHolder.getContext().getAuthentication().getName(); Account account = accountService.findAccountByUsername(username); - accountService.deposit(account, amount); + + try { + accountService.deposit(account, amount); + } catch (RuntimeException e) { + model.addAttribute("error", e.getMessage()); + model.addAttribute("account", account); + return "dashboard"; + } + return "redirect:/dashboard"; } diff --git a/src/main/java/com/example/bankapp/service/AccountService.java b/src/main/java/com/example/bankapp/service/AccountService.java index ba1a81ea..310a710a 100644 --- a/src/main/java/com/example/bankapp/service/AccountService.java +++ b/src/main/java/com/example/bankapp/service/AccountService.java @@ -35,7 +35,7 @@ public class AccountService implements UserDetailsService { private TransactionRepository transactionRepository; public Account findAccountByUsername(String username) { - return accountRepository.findByUsername(username).orElseThrow(() -> new RuntimeException("Account not found")); + return accountRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("Account not found")); } public Account registerAccount(String username, String password) { @@ -51,7 +51,14 @@ public Account registerAccount(String username, String password) { } + private void requirePositive(BigDecimal amount) { + if (amount == null || amount.signum() <= 0) { + throw new IllegalArgumentException("Amount must be greater than zero"); + } + } + public void deposit(Account account, BigDecimal amount) { + requirePositive(amount); account.setBalance(account.getBalance().add(amount)); accountRepository.save(account); @@ -68,10 +75,11 @@ public void deposit(Account account, BigDecimal amount) { * Returns true when the account balance is at least {@code amount}. */ public boolean hasSufficientFunds(Account account, BigDecimal amount) { - return account.getBalance().compareTo(amount) > 0; + return account.getBalance().compareTo(amount) >= 0; } public void withdraw(Account account, BigDecimal amount) { + requirePositive(amount); if (!hasSufficientFunds(account, amount)) { throw new RuntimeException("Insufficient funds"); } @@ -97,7 +105,7 @@ public List getTransactionHistory(Account account) { */ public List getTransactionHistory(Account account, LocalDate from, LocalDate to) { LocalDateTime start = from.atStartOfDay(); - LocalDateTime end = to.atStartOfDay(); + LocalDateTime end = to.plusDays(1).atStartOfDay(); return transactionRepository.findByAccountId(account.getId()).stream() .filter(t -> !t.getTimestamp().isBefore(start) && t.getTimestamp().isBefore(end)) .sorted(Comparator.comparing(Transaction::getTimestamp)) @@ -108,9 +116,6 @@ public List getTransactionHistory(Account account, LocalDate from, public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Account account = findAccountByUsername(username); - if (account == null) { - throw new UsernameNotFoundException("Username or Password not found"); - } return new Account( account.getUsername(), account.getPassword(), @@ -124,6 +129,7 @@ public Collection authorities() { } public void transferAmount(Account fromAccount, String toUsername, BigDecimal amount) { + requirePositive(amount); if (!hasSufficientFunds(fromAccount, amount)) { throw new RuntimeException("Insufficient funds"); } diff --git a/src/test/java/com/example/bankapp/controller/BankControllerDepositTest.java b/src/test/java/com/example/bankapp/controller/BankControllerDepositTest.java new file mode 100644 index 00000000..90e31250 --- /dev/null +++ b/src/test/java/com/example/bankapp/controller/BankControllerDepositTest.java @@ -0,0 +1,50 @@ +package com.example.bankapp.controller; + +import com.example.bankapp.repository.AccountRepository; +import com.example.bankapp.repository.TransactionRepository; +import com.example.bankapp.service.AccountService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +class BankControllerDepositTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private AccountService accountService; + + @Autowired + private AccountRepository accountRepository; + + @Autowired + private TransactionRepository transactionRepository; + + @BeforeEach + void setUp() { + transactionRepository.deleteAll(); + accountRepository.deleteAll(); + accountService.registerAccount("alice", "pw"); + } + + @Test + @WithMockUser(username = "alice") + void deposit_negativeAmountShowsErrorOnDashboard() throws Exception { + mockMvc.perform(post("/deposit").param("amount", "-50")) + .andExpect(status().isOk()) + .andExpect(view().name("dashboard")) + .andExpect(model().attribute("error", "Amount must be greater than zero")); + } +} diff --git a/src/test/java/com/example/bankapp/service/AccountServiceBugHuntTest.java b/src/test/java/com/example/bankapp/service/AccountServiceBugHuntTest.java new file mode 100644 index 00000000..dc567028 --- /dev/null +++ b/src/test/java/com/example/bankapp/service/AccountServiceBugHuntTest.java @@ -0,0 +1,121 @@ +package com.example.bankapp.service; + +import com.example.bankapp.model.Account; +import com.example.bankapp.model.Transaction; +import com.example.bankapp.repository.AccountRepository; +import com.example.bankapp.repository.TransactionRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.test.context.ActiveProfiles; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +@SpringBootTest +@ActiveProfiles("test") +class AccountServiceBugHuntTest { + + @Autowired + private AccountService accountService; + + @Autowired + private AccountRepository accountRepository; + + @Autowired + private TransactionRepository transactionRepository; + + private Account alice; + private Account bob; + + @BeforeEach + void setUp() { + transactionRepository.deleteAll(); + accountRepository.deleteAll(); + alice = accountService.registerAccount("alice", "pw"); + bob = accountService.registerAccount("bob", "pw"); + accountService.deposit(alice, new BigDecimal("100")); + } + + private BigDecimal balanceOf(String username) { + return accountService.findAccountByUsername(username).getBalance(); + } + + @Test + void hasSufficientFunds_isTrueWhenBalanceEqualsAmount() { + assertTrue(accountService.hasSufficientFunds(alice, new BigDecimal("100"))); + } + + @Test + void withdraw_entireBalanceSucceeds() { + accountService.withdraw(alice, new BigDecimal("100")); + assertEquals(0, balanceOf("alice").compareTo(BigDecimal.ZERO)); + } + + @Test + void transfer_entireBalanceSucceeds() { + accountService.transferAmount(alice, "bob", new BigDecimal("100")); + assertEquals(0, balanceOf("alice").compareTo(BigDecimal.ZERO)); + assertEquals(0, balanceOf("bob").compareTo(new BigDecimal("100"))); + } + + @Test + void transactionHistoryRange_includesTheToDay() { + LocalDate day = LocalDate.of(2026, 3, 10); + transactionRepository.save(new Transaction(new BigDecimal("5"), "Deposit", day.atTime(12, 0), alice)); + + List result = accountService.getTransactionHistory(alice, day, day); + + assertEquals(1, result.size()); + } + + @Test + void transactionHistoryRange_includesLastMinuteOfToDay() { + LocalDate from = LocalDate.of(2026, 3, 1); + LocalDate to = LocalDate.of(2026, 3, 10); + transactionRepository.save(new Transaction(new BigDecimal("5"), "Deposit", to.atTime(23, 59, 59), alice)); + transactionRepository.save(new Transaction(new BigDecimal("6"), "Deposit", to.plusDays(1).atStartOfDay(), alice)); + + List result = accountService.getTransactionHistory(alice, from, to); + + assertEquals(1, result.size()); + assertEquals(0, result.get(0).getAmount().compareTo(new BigDecimal("5"))); + } + + @Test + void transfer_negativeAmountIsRejected() { + accountService.deposit(bob, new BigDecimal("500")); + + assertThrows(RuntimeException.class, + () -> accountService.transferAmount(alice, "bob", new BigDecimal("-500"))); + + assertEquals(0, balanceOf("alice").compareTo(new BigDecimal("100"))); + assertEquals(0, balanceOf("bob").compareTo(new BigDecimal("500"))); + } + + @Test + void withdraw_negativeAmountIsRejected() { + assertThrows(RuntimeException.class, + () -> accountService.withdraw(alice, new BigDecimal("-1000"))); + assertEquals(0, balanceOf("alice").compareTo(new BigDecimal("100"))); + } + + @Test + void deposit_negativeAmountIsRejected() { + assertThrows(RuntimeException.class, + () -> accountService.deposit(alice, new BigDecimal("-1000"))); + assertEquals(0, balanceOf("alice").compareTo(new BigDecimal("100"))); + } + + @Test + void loadUserByUsername_unknownUserThrowsUsernameNotFoundException() { + assertThrows(UsernameNotFoundException.class, + () -> accountService.loadUserByUsername("nobody")); + } +}