Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions src/main/java/com/example/bankapp/controller/BankController.java
Original file line number Diff line number Diff line change
Expand Up @@ -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";
}

Expand Down
19 changes: 13 additions & 6 deletions src/main/java/com/example/bankapp/service/AccountService.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ public class AccountService implements UserDetailsService {
@Autowired
private TransactionRepository transactionRepository;

private static void requirePositive(BigDecimal amount) {
if (amount == null || amount.signum() <= 0) {
throw new RuntimeException("Amount must be greater than zero");
}
}

public Account findAccountByUsername(String username) {
return accountRepository.findByUsername(username).orElseThrow(() -> new RuntimeException("Account not found"));
}
Expand All @@ -52,6 +58,7 @@ public Account registerAccount(String username, String password) {


public void deposit(Account account, BigDecimal amount) {
requirePositive(amount);
account.setBalance(account.getBalance().add(amount));
accountRepository.save(account);

Expand All @@ -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");
}
Expand All @@ -97,7 +105,7 @@ public List<Transaction> getTransactionHistory(Account account) {
*/
public List<Transaction> 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))
Expand All @@ -107,10 +115,8 @@ public List<Transaction> getTransactionHistory(Account account, LocalDate from,
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

Account account = findAccountByUsername(username);
if (account == null) {
throw new UsernameNotFoundException("Username or Password not found");
}
Account account = accountRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("Username or Password not found"));
return new Account(
account.getUsername(),
account.getPassword(),
Expand All @@ -124,6 +130,7 @@ public Collection<? extends GrantedAuthority> authorities() {
}

public void transferAmount(Account fromAccount, String toUsername, BigDecimal amount) {
requirePositive(amount);
if (!hasSufficientFunds(fromAccount, amount)) {
throw new RuntimeException("Insufficient funds");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.example.bankapp.controller;

import com.example.bankapp.model.Account;
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.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 java.math.BigDecimal;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;

@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
class BankControllerDepositTest {

@Autowired
private MockMvc mockMvc;

@Autowired
private AccountRepository accountRepository;

@Autowired
private TransactionRepository transactionRepository;

@BeforeEach
void setUp() {
transactionRepository.deleteAll();
accountRepository.deleteAll();
Account account = new Account();
account.setUsername("carol");
account.setPassword("x");
account.setBalance(new BigDecimal("100.00"));
accountRepository.save(account);
}

@Test
@WithMockUser(username = "carol")
void negativeDeposit_showsErrorOnDashboardAndLeavesBalanceUnchanged() throws Exception {
mockMvc.perform(post("/deposit").param("amount", "-40.00"))
.andExpect(status().isOk())
.andExpect(view().name("dashboard"))
.andExpect(model().attributeExists("error"));

assertThat(accountRepository.findByUsername("carol").orElseThrow().getBalance())
.isEqualByComparingTo("100.00");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
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.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class AccountServiceBugHuntTest {

@Mock
private AccountRepository accountRepository;

@Mock
private TransactionRepository transactionRepository;

@InjectMocks
private AccountService accountService;

private Account alice;
private Account bob;

@BeforeEach
void setUp() {
alice = account(1L, "alice", "100.00");
bob = account(2L, "bob", "50.00");
lenient().when(accountRepository.findByUsername("bob")).thenReturn(Optional.of(bob));
}

private static Account account(Long id, String username, String balance) {
Account account = new Account();
account.setId(id);
account.setUsername(username);
account.setBalance(new BigDecimal(balance));
return account;
}

// Bug 1: hasSufficientFunds is documented as "at least" but uses a strict > comparison.
@Test
void hasSufficientFunds_isTrueWhenBalanceEqualsAmount() {
assertThat(accountService.hasSufficientFunds(alice, new BigDecimal("100.00"))).isTrue();
}

@Test
void withdraw_entireBalance_succeeds() {
accountService.withdraw(alice, new BigDecimal("100.00"));

assertThat(alice.getBalance()).isEqualByComparingTo("0");
}

@Test
void transfer_entireBalance_succeeds() {
accountService.transferAmount(alice, "bob", new BigDecimal("100.00"));

assertThat(alice.getBalance()).isEqualByComparingTo("0");
assertThat(bob.getBalance()).isEqualByComparingTo("150.00");
}

// Bug 2: the date-range history is documented as inclusive of both days but drops the whole "to" day.
@Test
void transactionHistoryByDate_includesTransactionsOnTheToDay() {
LocalDate day = LocalDate.of(2026, 11, 18);
Transaction morning = new Transaction(BigDecimal.TEN, "Deposit", day.atTime(9, 0), alice);
Transaction evening = new Transaction(BigDecimal.ONE, "Withdrawal", day.atTime(23, 59, 59), alice);
Transaction nextDay = new Transaction(BigDecimal.ONE, "Deposit", day.plusDays(1).atStartOfDay(), alice);
when(transactionRepository.findByAccountId(1L)).thenReturn(List.of(evening, nextDay, morning));

List<Transaction> result = accountService.getTransactionHistory(alice, day, day);

assertThat(result).containsExactly(morning, evening);
}

// Bug 3: non-positive amounts are accepted and move money in the wrong direction.
@Test
void deposit_negativeAmount_isRejected() {
assertThatThrownBy(() -> accountService.deposit(alice, new BigDecimal("-50.00")))
.isInstanceOf(RuntimeException.class);
assertThat(alice.getBalance()).isEqualByComparingTo("100.00");
verify(transactionRepository, never()).save(any());
}

@Test
void withdraw_negativeAmount_isRejected() {
assertThatThrownBy(() -> accountService.withdraw(alice, new BigDecimal("-50.00")))
.isInstanceOf(RuntimeException.class);
assertThat(alice.getBalance()).isEqualByComparingTo("100.00");
verify(transactionRepository, never()).save(any());
}

@Test
void transfer_negativeAmount_doesNotPullMoneyFromRecipient() {
assertThatThrownBy(() -> accountService.transferAmount(alice, "bob", new BigDecimal("-30.00")))
.isInstanceOf(RuntimeException.class);
assertThat(alice.getBalance()).isEqualByComparingTo("100.00");
assertThat(bob.getBalance()).isEqualByComparingTo("50.00");
verify(transactionRepository, never()).save(any());
}

@Test
void transfer_zeroAmount_isRejected() {
assertThatThrownBy(() -> accountService.transferAmount(alice, "bob", BigDecimal.ZERO))
.isInstanceOf(RuntimeException.class);
verify(transactionRepository, never()).save(any());
}

// Bug 4: UserDetailsService contract requires UsernameNotFoundException for unknown users.
@Test
void loadUserByUsername_unknownUser_throwsUsernameNotFoundException() {
when(accountRepository.findByUsername("ghost")).thenReturn(Optional.empty());

assertThatThrownBy(() -> accountService.loadUserByUsername("ghost"))
.isInstanceOf(UsernameNotFoundException.class);
}
}
Loading