diff --git a/docs/LEARNINGS.md b/docs/LEARNINGS.md new file mode 100644 index 00000000..dbc239f7 --- /dev/null +++ b/docs/LEARNINGS.md @@ -0,0 +1,143 @@ +# Learnings: Async Payment Migration & Transactional Safety + +This document captures key technical insights from migrating the BankApp's synchronous payment flows to async patterns while maintaining transactional integrity. + +--- + +## 1. Spring @Async Internals + +### How Spring Proxies Async Methods + +Spring's `@Async` works through AOP proxying. When a bean method is annotated with `@Async`, Spring wraps the bean in a proxy that intercepts calls and submits them to a `TaskExecutor` instead of executing on the caller's thread. The actual method runs on a thread from the configured executor pool. + +**Critical gotcha — self-invocation doesn't work with @Async.** If `ServiceA.methodA()` calls `this.methodB()` where `methodB()` is `@Async`, the call bypasses the proxy and executes synchronously. This is because `this` refers to the raw bean, not the proxy. The solution is to inject the service into itself or extract async methods into a separate service (which is what we did with `TransactionLoggingService`). + +### TaskExecutor Thread Pool Management + +The `ThreadPoolTaskExecutor` configured in `AsyncConfig` manages a pool with: +- **Core pool size (5):** Threads kept alive even when idle +- **Max pool size (10):** Upper bound when queue is full +- **Queue capacity (25):** Buffered tasks before spawning beyond core + +Thread naming via `setThreadNamePrefix("payment-async-")` is critical for debugging — it lets you trace in logs which operations are running asynchronously vs. synchronously. When we see log lines from the `payment-async-1` thread, we know the transaction logging is correctly offloaded. + +--- + +## 2. @Transactional + @Async Interaction + +### Why You Cannot Combine Both on the Same Method + +Spring's `@Transactional` binds a transaction to the **current thread** via `ThreadLocal`. When `@Async` moves execution to a different thread, the transaction context does **not** propagate. This means: + +``` +@Transactional +@Async +public void doWork() { + // The @Transactional has NO effect here because @Async + // runs this on a new thread with no transaction context + repository.save(entity); // runs without transactional protection +} +``` + +If both annotations are on the same method, one of two things happens depending on proxy ordering: +1. If `@Async` is processed first, the method runs on a new thread without the caller's transaction +2. If `@Transactional` is processed first, it creates a transaction on the new async thread — but this is a **separate** transaction from the caller, defeating the purpose of atomicity + +### The Pattern: Sync Writes + Async Audit + +The correct architecture separates concerns: +- **Critical path (balance updates):** Synchronous + `@Transactional` in `AccountService`. The `deposit()`, `withdraw()`, and `transferAmount()` methods mutate balances and save accounts within a single transaction. +- **Audit trail (transaction logging):** Asynchronous in `TransactionLoggingService`. Creating `Transaction` records is non-critical and can be offloaded to the thread pool. If async logging fails, the balance is still correct. + +This separation means a failed transaction log doesn't roll back a successful balance update, which is the correct business behavior for a banking application — the balance is the source of truth, and the audit trail is eventually consistent. + +--- + +## 3. CompletableFuture Patterns + +### Composing Async Results + +`CompletableFuture` enables non-blocking composition: + +```java +// Sequential composition +CompletableFuture result = logDepositAsync(account, amount) + .thenApply(tx -> { tx.setStatus(COMPLETED); return tx; }); + +// Parallel composition +CompletableFuture.allOf( + logTransferAsync(sender, amount, "Transfer Out"), + logTransferAsync(recipient, amount, "Transfer In") +).join(); +``` + +### Exception Handling in Async Chains + +Exceptions in `CompletableFuture.supplyAsync()` are wrapped in `CompletionException`. In the REST controller, we catch `RuntimeException` inside the supplier to return proper HTTP error responses: + +```java +CompletableFuture.supplyAsync(() -> { + try { + accountService.withdraw(account, amount); + } catch (RuntimeException e) { + return ResponseEntity.badRequest().body(Map.of("error", e.getMessage())); + } + return ResponseEntity.ok(response); +}, paymentTaskExecutor); +``` + +### Testing Async Code + +Key testing insight: `@Transactional` test annotations don't work with async endpoints because the test transaction lives on the test thread, while the async handler runs on the executor thread (which can't see uncommitted data). The fix is to **not** use `@Transactional` on async integration tests and instead use explicit `@BeforeEach`/`@AfterEach` cleanup. + +For MockMvc async tests, the pattern is: +```java +MvcResult result = mockMvc.perform(post("/api/deposit").param("amount", "500")) + .andExpect(request().asyncStarted()) + .andReturn(); + +mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.newBalance").value(1500.00)); +``` + +--- + +## 4. Race Conditions in Financial Systems + +### The Lost Update Problem + +Without `@Transactional`, the `transferAmount()` method performed 4 separate DB writes: +1. Debit sender account +2. Save sender +3. Credit recipient account +4. Save recipient + +If two concurrent transfers happen simultaneously, both could read the same initial balance, compute new balances independently, and write back — causing one transfer to be "lost." This is the classic lost update anomaly. + +### How @Transactional Prevents Lost Updates + +Adding `@Transactional` wraps all 4 operations in a single database transaction. With the default isolation level (`READ_COMMITTED` on most databases), this provides: +- **Atomicity:** Either all 4 writes succeed or none do. If saving the recipient fails, the sender's debit is rolled back. +- **Row-level locking:** When Hibernate loads and modifies an account, the row is locked until the transaction commits, preventing concurrent modifications. + +For higher-contention scenarios, you could escalate to `SERIALIZABLE` isolation or use optimistic locking with `@Version`, but `READ_COMMITTED` + `@Transactional` is sufficient for this application's concurrency profile. + +### SecurityContext and Thread Boundaries + +A subtle but critical finding: `SecurityContextHolder` stores the authentication context in a `ThreadLocal`. When using `CompletableFuture.supplyAsync()`, the async thread does **not** inherit the security context. The solution is to capture the username synchronously on the HTTP request thread and pass it as a closure variable to the async supplier: + +```java +// Capture on request thread (has SecurityContext) +String username = SecurityContextHolder.getContext().getAuthentication().getName(); + +// Use captured value on async thread (no SecurityContext) +return CompletableFuture.supplyAsync(() -> { + Account account = accountService.findAccountByUsername(username); + // ... +}, paymentTaskExecutor); +``` + +### H2 Reserved Keywords + +The entity name `Transaction` maps to a table name `transaction`, which is a SQL reserved keyword. H2 in test mode rejects this. Renaming the table via `@Table(name = "bank_transaction")` resolves the issue without affecting MySQL in production (where `transaction` may be quoted automatically by the dialect). diff --git a/pom.xml b/pom.xml index fc5bfeac..eed97c9e 100644 --- a/pom.xml +++ b/pom.xml @@ -57,6 +57,11 @@ 8.0.33 runtime + + com.h2database + h2 + test + org.springframework.boot spring-boot-starter-test diff --git a/src/main/java/com/example/bankapp/config/AsyncConfig.java b/src/main/java/com/example/bankapp/config/AsyncConfig.java new file mode 100644 index 00000000..4477b07a --- /dev/null +++ b/src/main/java/com/example/bankapp/config/AsyncConfig.java @@ -0,0 +1,24 @@ +package com.example.bankapp.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.Executor; + +@Configuration +@EnableAsync +public class AsyncConfig { + + @Bean(name = "paymentTaskExecutor") + public Executor paymentTaskExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(5); + executor.setMaxPoolSize(10); + executor.setQueueCapacity(25); + executor.setThreadNamePrefix("payment-async-"); + executor.initialize(); + return executor; + } +} diff --git a/src/main/java/com/example/bankapp/config/SecurityConfig.java b/src/main/java/com/example/bankapp/config/SecurityConfig.java index 4dbd1572..e0636035 100644 --- a/src/main/java/com/example/bankapp/config/SecurityConfig.java +++ b/src/main/java/com/example/bankapp/config/SecurityConfig.java @@ -30,6 +30,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti .csrf(csrf -> csrf.disable()) .authorizeHttpRequests(authz -> authz .requestMatchers("/register").permitAll() + .requestMatchers("/api/**").authenticated() .anyRequest().authenticated() ) .formLogin(form -> form diff --git a/src/main/java/com/example/bankapp/controller/BankRestController.java b/src/main/java/com/example/bankapp/controller/BankRestController.java new file mode 100644 index 00000000..be2c9248 --- /dev/null +++ b/src/main/java/com/example/bankapp/controller/BankRestController.java @@ -0,0 +1,114 @@ +package com.example.bankapp.controller; + +import com.example.bankapp.model.Account; +import com.example.bankapp.model.Transaction; +import com.example.bankapp.service.AccountService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; + +@RestController +@RequestMapping("/api") +public class BankRestController { + + @Autowired + private AccountService accountService; + + @Autowired + @Qualifier("paymentTaskExecutor") + private Executor paymentTaskExecutor; + + @PostMapping("/deposit") + public CompletableFuture>> deposit(@RequestParam BigDecimal amount) { + String username = SecurityContextHolder.getContext().getAuthentication().getName(); + return CompletableFuture.supplyAsync(() -> { + Account account = accountService.findAccountByUsername(username); + + try { + accountService.deposit(account, amount); + } catch (RuntimeException e) { + Map errorResponse = new HashMap<>(); + errorResponse.put("error", e.getMessage()); + return ResponseEntity.badRequest().body(errorResponse); + } + + Account updated = accountService.findAccountByUsername(username); + Map response = new HashMap<>(); + response.put("message", "Deposit successful"); + response.put("newBalance", updated.getBalance()); + response.put("amount", amount); + return ResponseEntity.ok(response); + }, paymentTaskExecutor); + } + + @PostMapping("/withdraw") + public CompletableFuture>> withdraw(@RequestParam BigDecimal amount) { + String username = SecurityContextHolder.getContext().getAuthentication().getName(); + return CompletableFuture.supplyAsync(() -> { + Account account = accountService.findAccountByUsername(username); + + try { + accountService.withdraw(account, amount); + } catch (RuntimeException e) { + Map errorResponse = new HashMap<>(); + errorResponse.put("error", e.getMessage()); + return ResponseEntity.badRequest().body(errorResponse); + } + + Account updated = accountService.findAccountByUsername(username); + Map response = new HashMap<>(); + response.put("message", "Withdrawal successful"); + response.put("newBalance", updated.getBalance()); + response.put("amount", amount); + return ResponseEntity.ok(response); + }, paymentTaskExecutor); + } + + @PostMapping("/transfer") + public CompletableFuture>> transfer( + @RequestParam String toUsername, @RequestParam BigDecimal amount) { + String username = SecurityContextHolder.getContext().getAuthentication().getName(); + return CompletableFuture.supplyAsync(() -> { + Account fromAccount = accountService.findAccountByUsername(username); + + try { + accountService.transferAmount(fromAccount, toUsername, amount); + } catch (RuntimeException e) { + Map errorResponse = new HashMap<>(); + errorResponse.put("error", e.getMessage()); + return ResponseEntity.badRequest().body(errorResponse); + } + + Account updated = accountService.findAccountByUsername(username); + Map response = new HashMap<>(); + response.put("message", "Transfer successful"); + response.put("newBalance", updated.getBalance()); + response.put("amount", amount); + response.put("recipient", toUsername); + return ResponseEntity.ok(response); + }, paymentTaskExecutor); + } + + @GetMapping("/transactions") + public CompletableFuture>> transactions() { + String username = SecurityContextHolder.getContext().getAuthentication().getName(); + return CompletableFuture.supplyAsync(() -> { + Account account = accountService.findAccountByUsername(username); + List history = accountService.getTransactionHistory(account); + return ResponseEntity.ok(history); + }, paymentTaskExecutor); + } +} diff --git a/src/main/java/com/example/bankapp/model/Transaction.java b/src/main/java/com/example/bankapp/model/Transaction.java index b3f371f9..129f304d 100644 --- a/src/main/java/com/example/bankapp/model/Transaction.java +++ b/src/main/java/com/example/bankapp/model/Transaction.java @@ -1,10 +1,12 @@ package com.example.bankapp.model; +import com.fasterxml.jackson.annotation.JsonIgnore; import jakarta.persistence.*; import java.math.BigDecimal; import java.time.LocalDateTime; @Entity +@Table(name = "bank_transaction") public class Transaction { @Id @@ -14,8 +16,12 @@ public class Transaction { private String type; private LocalDateTime timestamp; + @Enumerated(EnumType.STRING) + private TransactionStatus status = TransactionStatus.PENDING; + @ManyToOne @JoinColumn(name = "account_id") + @JsonIgnore private Account account; public Transaction() { @@ -27,6 +33,7 @@ public Transaction(BigDecimal amount, String type, LocalDateTime timestamp, Acco this.type = type; this.timestamp = timestamp; this.account = account; + this.status = TransactionStatus.PENDING; } public Long getId() { @@ -68,4 +75,12 @@ public Account getAccount() { public void setAccount(Account account) { this.account = account; } + + public TransactionStatus getStatus() { + return status; + } + + public void setStatus(TransactionStatus status) { + this.status = status; + } } diff --git a/src/main/java/com/example/bankapp/model/TransactionStatus.java b/src/main/java/com/example/bankapp/model/TransactionStatus.java new file mode 100644 index 00000000..8bee7612 --- /dev/null +++ b/src/main/java/com/example/bankapp/model/TransactionStatus.java @@ -0,0 +1,7 @@ +package com.example.bankapp.model; + +public enum TransactionStatus { + PENDING, + COMPLETED, + FAILED +} diff --git a/src/main/java/com/example/bankapp/service/AccountService.java b/src/main/java/com/example/bankapp/service/AccountService.java index 5d7d90ec..74ae58b3 100644 --- a/src/main/java/com/example/bankapp/service/AccountService.java +++ b/src/main/java/com/example/bankapp/service/AccountService.java @@ -12,9 +12,9 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; -import java.time.LocalDateTime; import java.util.Arrays; import java.util.Collection; import java.util.List; @@ -31,6 +31,9 @@ public class AccountService implements UserDetailsService { @Autowired private TransactionRepository transactionRepository; + @Autowired + private TransactionLoggingService transactionLoggingService; + public Account findAccountByUsername(String username) { return accountRepository.findByUsername(username).orElseThrow(() -> new RuntimeException("Account not found")); } @@ -48,33 +51,27 @@ public Account registerAccount(String username, String password) { } + @Transactional public void deposit(Account account, BigDecimal amount) { - account.setBalance(account.getBalance().add(amount)); - accountRepository.save(account); - - Transaction transaction = new Transaction( - amount, - "Deposit", - LocalDateTime.now(), - account - ); - transactionRepository.save(transaction); + Account freshAccount = accountRepository.findById(account.getId()) + .orElseThrow(() -> new RuntimeException("Account not found")); + freshAccount.setBalance(freshAccount.getBalance().add(amount)); + accountRepository.save(freshAccount); + + transactionLoggingService.logDepositAsync(freshAccount, amount); } + @Transactional public void withdraw(Account account, BigDecimal amount) { - if (account.getBalance().compareTo(amount) < 0) { + Account freshAccount = accountRepository.findById(account.getId()) + .orElseThrow(() -> new RuntimeException("Account not found")); + if (freshAccount.getBalance().compareTo(amount) < 0) { throw new RuntimeException("Insufficient funds"); } - account.setBalance(account.getBalance().subtract(amount)); - accountRepository.save(account); - - Transaction transaction = new Transaction( - amount, - "Withdrawal", - LocalDateTime.now(), - account - ); - transactionRepository.save(transaction); + freshAccount.setBalance(freshAccount.getBalance().subtract(amount)); + accountRepository.save(freshAccount); + + transactionLoggingService.logWithdrawalAsync(freshAccount, amount); } public List getTransactionHistory(Account account) { @@ -100,38 +97,27 @@ public Collection authorities() { return Arrays.asList(new SimpleGrantedAuthority("USER")); } + @Transactional public void transferAmount(Account fromAccount, String toUsername, BigDecimal amount) { - if (fromAccount.getBalance().compareTo(amount) < 0) { + Account freshFrom = accountRepository.findById(fromAccount.getId()) + .orElseThrow(() -> new RuntimeException("Account not found")); + if (freshFrom.getBalance().compareTo(amount) < 0) { throw new RuntimeException("Insufficient funds"); } Account toAccount = accountRepository.findByUsername(toUsername) .orElseThrow(() -> new RuntimeException("Recipient account not found")); - // Deduct from sender's account - fromAccount.setBalance(fromAccount.getBalance().subtract(amount)); - accountRepository.save(fromAccount); + freshFrom.setBalance(freshFrom.getBalance().subtract(amount)); + accountRepository.save(freshFrom); - // Add to recipient's account toAccount.setBalance(toAccount.getBalance().add(amount)); accountRepository.save(toAccount); - // Create transaction records for both accounts - Transaction debitTransaction = new Transaction( - amount, - "Transfer Out to " + toAccount.getUsername(), - LocalDateTime.now(), - fromAccount - ); - transactionRepository.save(debitTransaction); - - Transaction creditTransaction = new Transaction( - amount, - "Transfer In from " + fromAccount.getUsername(), - LocalDateTime.now(), - toAccount - ); - transactionRepository.save(creditTransaction); + transactionLoggingService.logTransferAsync( + freshFrom, amount, "Transfer Out to " + toAccount.getUsername()); + transactionLoggingService.logTransferAsync( + toAccount, amount, "Transfer In from " + freshFrom.getUsername()); } } diff --git a/src/main/java/com/example/bankapp/service/TransactionLoggingService.java b/src/main/java/com/example/bankapp/service/TransactionLoggingService.java new file mode 100644 index 00000000..7ae59468 --- /dev/null +++ b/src/main/java/com/example/bankapp/service/TransactionLoggingService.java @@ -0,0 +1,51 @@ +package com.example.bankapp.service; + +import com.example.bankapp.model.Account; +import com.example.bankapp.model.Transaction; +import com.example.bankapp.model.TransactionStatus; +import com.example.bankapp.repository.TransactionRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.concurrent.CompletableFuture; + +@Service +public class TransactionLoggingService { + + private static final Logger logger = LoggerFactory.getLogger(TransactionLoggingService.class); + + @Autowired + private TransactionRepository transactionRepository; + + @Async("paymentTaskExecutor") + public CompletableFuture logDepositAsync(Account account, BigDecimal amount) { + logger.info("Logging deposit asynchronously on thread: {}", Thread.currentThread().getName()); + Transaction transaction = new Transaction(amount, "Deposit", LocalDateTime.now(), account); + transaction.setStatus(TransactionStatus.COMPLETED); + Transaction saved = transactionRepository.save(transaction); + return CompletableFuture.completedFuture(saved); + } + + @Async("paymentTaskExecutor") + public CompletableFuture logWithdrawalAsync(Account account, BigDecimal amount) { + logger.info("Logging withdrawal asynchronously on thread: {}", Thread.currentThread().getName()); + Transaction transaction = new Transaction(amount, "Withdrawal", LocalDateTime.now(), account); + transaction.setStatus(TransactionStatus.COMPLETED); + Transaction saved = transactionRepository.save(transaction); + return CompletableFuture.completedFuture(saved); + } + + @Async("paymentTaskExecutor") + public CompletableFuture logTransferAsync(Account account, BigDecimal amount, String type) { + logger.info("Logging transfer asynchronously on thread: {}", Thread.currentThread().getName()); + Transaction transaction = new Transaction(amount, type, LocalDateTime.now(), account); + transaction.setStatus(TransactionStatus.COMPLETED); + Transaction saved = transactionRepository.save(transaction); + return CompletableFuture.completedFuture(saved); + } +} diff --git a/src/test/java/com/example/bankapp/BankappApplicationTests.java b/src/test/java/com/example/bankapp/BankappApplicationTests.java index 63c64e9d..6184e848 100644 --- a/src/test/java/com/example/bankapp/BankappApplicationTests.java +++ b/src/test/java/com/example/bankapp/BankappApplicationTests.java @@ -2,8 +2,10 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; @SpringBootTest +@ActiveProfiles("test") class BankappApplicationTests { @Test diff --git a/src/test/java/com/example/bankapp/controller/BankControllerTest.java b/src/test/java/com/example/bankapp/controller/BankControllerTest.java new file mode 100644 index 00000000..5d873291 --- /dev/null +++ b/src/test/java/com/example/bankapp/controller/BankControllerTest.java @@ -0,0 +1,165 @@ +package com.example.bankapp.controller; + +import com.example.bankapp.model.Account; +import com.example.bankapp.model.Transaction; +import com.example.bankapp.model.TransactionStatus; +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.crypto.password.PasswordEncoder; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import static org.hamcrest.Matchers.containsString; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@Transactional +class BankControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private AccountRepository accountRepository; + + @Autowired + private TransactionRepository transactionRepository; + + @Autowired + private PasswordEncoder passwordEncoder; + + private Account testAccount; + + @BeforeEach + void setUp() { + transactionRepository.deleteAll(); + accountRepository.deleteAll(); + + testAccount = new Account(); + testAccount.setUsername("testuser"); + testAccount.setPassword(passwordEncoder.encode("password")); + testAccount.setBalance(new BigDecimal("1000.00")); + testAccount = accountRepository.save(testAccount); + } + + @Test + @WithMockUser(username = "testuser") + void deposit_shouldRedirectToDashboard() throws Exception { + mockMvc.perform(post("/deposit").param("amount", "500")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("/dashboard")); + + Account updated = accountRepository.findByUsername("testuser").orElseThrow(); + assert updated.getBalance().compareTo(new BigDecimal("1500.00")) == 0; + } + + @Test + @WithMockUser(username = "testuser") + void withdraw_shouldRedirectToDashboard() throws Exception { + mockMvc.perform(post("/withdraw").param("amount", "300")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("/dashboard")); + + Account updated = accountRepository.findByUsername("testuser").orElseThrow(); + assert updated.getBalance().compareTo(new BigDecimal("700.00")) == 0; + } + + @Test + @WithMockUser(username = "testuser") + void withdraw_withInsufficientFunds_shouldShowError() throws Exception { + mockMvc.perform(post("/withdraw").param("amount", "2000")) + .andExpect(status().isOk()) + .andExpect(view().name("dashboard")) + .andExpect(model().attributeExists("error")); + } + + @Test + @WithMockUser(username = "testuser") + void transfer_shouldRedirectToDashboard() throws Exception { + Account recipient = new Account(); + recipient.setUsername("recipient"); + recipient.setPassword(passwordEncoder.encode("password")); + recipient.setBalance(new BigDecimal("500.00")); + accountRepository.save(recipient); + + mockMvc.perform(post("/transfer") + .param("toUsername", "recipient") + .param("amount", "200")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("/dashboard")); + + Account updatedSender = accountRepository.findByUsername("testuser").orElseThrow(); + Account updatedRecipient = accountRepository.findByUsername("recipient").orElseThrow(); + assert updatedSender.getBalance().compareTo(new BigDecimal("800.00")) == 0; + assert updatedRecipient.getBalance().compareTo(new BigDecimal("700.00")) == 0; + } + + @Test + @WithMockUser(username = "testuser") + void transfer_toNonExistentUser_shouldShowError() throws Exception { + mockMvc.perform(post("/transfer") + .param("toUsername", "nonexistent") + .param("amount", "100")) + .andExpect(status().isOk()) + .andExpect(view().name("dashboard")) + .andExpect(model().attributeExists("error")); + } + + @Test + @WithMockUser(username = "testuser") + void transactions_shouldShowTransactionHistory() throws Exception { + Transaction transaction = new Transaction( + new BigDecimal("100.00"), "Deposit", LocalDateTime.now(), testAccount); + transaction.setStatus(TransactionStatus.COMPLETED); + transactionRepository.save(transaction); + + mockMvc.perform(get("/transactions")) + .andExpect(status().isOk()) + .andExpect(view().name("transactions")) + .andExpect(model().attributeExists("transactions")); + } + + @Test + @WithMockUser(username = "testuser") + void dashboard_shouldDisplayAccountInfo() throws Exception { + mockMvc.perform(get("/dashboard")) + .andExpect(status().isOk()) + .andExpect(view().name("dashboard")) + .andExpect(model().attributeExists("account")); + } + + @Test + void register_shouldCreateAccountAndRedirect() throws Exception { + mockMvc.perform(post("/register") + .param("username", "newuser") + .param("password", "newpassword")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("/login")); + + assert accountRepository.findByUsername("newuser").isPresent(); + } + + @Test + void register_withDuplicate_shouldShowError() throws Exception { + mockMvc.perform(post("/register") + .param("username", "testuser") + .param("password", "password")) + .andExpect(status().isOk()) + .andExpect(view().name("register")) + .andExpect(model().attributeExists("error")); + } +} diff --git a/src/test/java/com/example/bankapp/controller/BankRestControllerTest.java b/src/test/java/com/example/bankapp/controller/BankRestControllerTest.java new file mode 100644 index 00000000..b33dcc20 --- /dev/null +++ b/src/test/java/com/example/bankapp/controller/BankRestControllerTest.java @@ -0,0 +1,180 @@ +package com.example.bankapp.controller; + +import com.example.bankapp.model.Account; +import com.example.bankapp.model.Transaction; +import com.example.bankapp.model.TransactionStatus; +import com.example.bankapp.repository.AccountRepository; +import com.example.bankapp.repository.TransactionRepository; +import org.junit.jupiter.api.AfterEach; +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.crypto.password.PasswordEncoder; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import static org.hamcrest.Matchers.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +class BankRestControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private AccountRepository accountRepository; + + @Autowired + private TransactionRepository transactionRepository; + + @Autowired + private PasswordEncoder passwordEncoder; + + private Account testAccount; + + @BeforeEach + void setUp() { + transactionRepository.deleteAll(); + accountRepository.deleteAll(); + + testAccount = new Account(); + testAccount.setUsername("testuser"); + testAccount.setPassword(passwordEncoder.encode("password")); + testAccount.setBalance(new BigDecimal("1000.00")); + testAccount = accountRepository.save(testAccount); + } + + @AfterEach + void tearDown() { + transactionRepository.deleteAll(); + accountRepository.deleteAll(); + } + + @Test + @WithMockUser(username = "testuser") + void deposit_shouldReturnJsonWithUpdatedBalance() throws Exception { + MvcResult result = mockMvc.perform(post("/api/deposit").param("amount", "500")) + .andExpect(request().asyncStarted()) + .andReturn(); + + mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.message").value("Deposit successful")) + .andExpect(jsonPath("$.newBalance").value(1500.00)) + .andExpect(jsonPath("$.amount").value(500)); + } + + @Test + @WithMockUser(username = "testuser") + void withdraw_shouldReturnJsonWithUpdatedBalance() throws Exception { + MvcResult result = mockMvc.perform(post("/api/withdraw").param("amount", "300")) + .andExpect(request().asyncStarted()) + .andReturn(); + + mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.message").value("Withdrawal successful")) + .andExpect(jsonPath("$.newBalance").value(700.00)) + .andExpect(jsonPath("$.amount").value(300)); + } + + @Test + @WithMockUser(username = "testuser") + void withdraw_withInsufficientFunds_shouldReturnError() throws Exception { + MvcResult result = mockMvc.perform(post("/api/withdraw").param("amount", "2000")) + .andExpect(request().asyncStarted()) + .andReturn(); + + mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Insufficient funds")); + } + + @Test + @WithMockUser(username = "testuser") + void transfer_shouldReturnJsonWithConfirmation() throws Exception { + Account recipient = new Account(); + recipient.setUsername("recipient"); + recipient.setPassword(passwordEncoder.encode("password")); + recipient.setBalance(new BigDecimal("500.00")); + accountRepository.save(recipient); + + MvcResult result = mockMvc.perform(post("/api/transfer") + .param("toUsername", "recipient") + .param("amount", "200")) + .andExpect(request().asyncStarted()) + .andReturn(); + + mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.message").value("Transfer successful")) + .andExpect(jsonPath("$.newBalance").value(800.00)) + .andExpect(jsonPath("$.recipient").value("recipient")); + } + + @Test + @WithMockUser(username = "testuser") + void transfer_toNonExistentUser_shouldReturnError() throws Exception { + MvcResult result = mockMvc.perform(post("/api/transfer") + .param("toUsername", "nonexistent") + .param("amount", "100")) + .andExpect(request().asyncStarted()) + .andReturn(); + + mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Recipient account not found")); + } + + @Test + @WithMockUser(username = "testuser") + void transactions_shouldReturnJsonList() throws Exception { + Transaction transaction = new Transaction( + new BigDecimal("100.00"), "Deposit", LocalDateTime.now(), testAccount); + transaction.setStatus(TransactionStatus.COMPLETED); + transactionRepository.save(transaction); + + MvcResult result = mockMvc.perform(get("/api/transactions")) + .andExpect(request().asyncStarted()) + .andReturn(); + + mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(1))) + .andExpect(jsonPath("$[0].type").value("Deposit")) + .andExpect(jsonPath("$[0].amount").value(100.00)); + } + + @Test + @WithMockUser(username = "testuser") + void transfer_withInsufficientFunds_shouldReturnError() throws Exception { + Account recipient = new Account(); + recipient.setUsername("recipient"); + recipient.setPassword(passwordEncoder.encode("password")); + recipient.setBalance(new BigDecimal("500.00")); + accountRepository.save(recipient); + + MvcResult result = mockMvc.perform(post("/api/transfer") + .param("toUsername", "recipient") + .param("amount", "5000")) + .andExpect(request().asyncStarted()) + .andReturn(); + + mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Insufficient funds")); + } +} diff --git a/src/test/java/com/example/bankapp/service/AccountServiceTest.java b/src/test/java/com/example/bankapp/service/AccountServiceTest.java new file mode 100644 index 00000000..bcd1bf05 --- /dev/null +++ b/src/test/java/com/example/bankapp/service/AccountServiceTest.java @@ -0,0 +1,242 @@ +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.crypto.password.PasswordEncoder; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class AccountServiceTest { + + @Mock + private AccountRepository accountRepository; + + @Mock + private TransactionRepository transactionRepository; + + @Mock + private TransactionLoggingService transactionLoggingService; + + @Mock + private PasswordEncoder passwordEncoder; + + @InjectMocks + private AccountService accountService; + + private Account testAccount; + + @BeforeEach + void setUp() { + testAccount = new Account(); + testAccount.setId(1L); + testAccount.setUsername("testuser"); + testAccount.setPassword("encodedPassword"); + testAccount.setBalance(new BigDecimal("1000.00")); + } + + @Test + void deposit_shouldIncreaseBalance() { + BigDecimal depositAmount = new BigDecimal("500.00"); + when(accountRepository.findById(1L)).thenReturn(Optional.of(testAccount)); + when(accountRepository.save(any(Account.class))).thenReturn(testAccount); + when(transactionLoggingService.logDepositAsync(any(Account.class), any(BigDecimal.class))) + .thenReturn(CompletableFuture.completedFuture(new Transaction())); + + accountService.deposit(testAccount, depositAmount); + + assertEquals(new BigDecimal("1500.00"), testAccount.getBalance()); + verify(accountRepository).save(testAccount); + verify(transactionLoggingService).logDepositAsync(testAccount, depositAmount); + } + + @Test + void deposit_withZeroAmount_shouldStillProcess() { + BigDecimal depositAmount = BigDecimal.ZERO; + when(accountRepository.findById(1L)).thenReturn(Optional.of(testAccount)); + when(accountRepository.save(any(Account.class))).thenReturn(testAccount); + when(transactionLoggingService.logDepositAsync(any(Account.class), any(BigDecimal.class))) + .thenReturn(CompletableFuture.completedFuture(new Transaction())); + + accountService.deposit(testAccount, depositAmount); + + assertEquals(new BigDecimal("1000.00"), testAccount.getBalance()); + verify(accountRepository).save(testAccount); + } + + @Test + void withdraw_shouldDecreaseBalance() { + BigDecimal withdrawAmount = new BigDecimal("300.00"); + when(accountRepository.findById(1L)).thenReturn(Optional.of(testAccount)); + when(accountRepository.save(any(Account.class))).thenReturn(testAccount); + when(transactionLoggingService.logWithdrawalAsync(any(Account.class), any(BigDecimal.class))) + .thenReturn(CompletableFuture.completedFuture(new Transaction())); + + accountService.withdraw(testAccount, withdrawAmount); + + assertEquals(new BigDecimal("700.00"), testAccount.getBalance()); + verify(accountRepository).save(testAccount); + verify(transactionLoggingService).logWithdrawalAsync(testAccount, withdrawAmount); + } + + @Test + void withdraw_withInsufficientFunds_shouldThrowException() { + BigDecimal withdrawAmount = new BigDecimal("1500.00"); + when(accountRepository.findById(1L)).thenReturn(Optional.of(testAccount)); + + RuntimeException exception = assertThrows(RuntimeException.class, + () -> accountService.withdraw(testAccount, withdrawAmount)); + + assertEquals("Insufficient funds", exception.getMessage()); + verify(accountRepository, never()).save(any()); + verify(transactionLoggingService, never()).logWithdrawalAsync(any(), any()); + } + + @Test + void transferAmount_shouldDebitSenderAndCreditRecipient() { + Account recipientAccount = new Account(); + recipientAccount.setId(2L); + recipientAccount.setUsername("recipient"); + recipientAccount.setBalance(new BigDecimal("500.00")); + + BigDecimal transferAmount = new BigDecimal("200.00"); + + when(accountRepository.findById(1L)).thenReturn(Optional.of(testAccount)); + when(accountRepository.findByUsername("recipient")).thenReturn(Optional.of(recipientAccount)); + when(accountRepository.save(any(Account.class))).thenAnswer(i -> i.getArgument(0)); + when(transactionLoggingService.logTransferAsync(any(Account.class), any(BigDecimal.class), anyString())) + .thenReturn(CompletableFuture.completedFuture(new Transaction())); + + accountService.transferAmount(testAccount, "recipient", transferAmount); + + assertEquals(new BigDecimal("800.00"), testAccount.getBalance()); + assertEquals(new BigDecimal("700.00"), recipientAccount.getBalance()); + verify(accountRepository, times(2)).save(any(Account.class)); + verify(transactionLoggingService, times(2)).logTransferAsync(any(), eq(transferAmount), anyString()); + } + + @Test + void transferAmount_withInsufficientFunds_shouldThrowException() { + BigDecimal transferAmount = new BigDecimal("2000.00"); + when(accountRepository.findById(1L)).thenReturn(Optional.of(testAccount)); + + RuntimeException exception = assertThrows(RuntimeException.class, + () -> accountService.transferAmount(testAccount, "recipient", transferAmount)); + + assertEquals("Insufficient funds", exception.getMessage()); + verify(accountRepository, never()).save(any()); + } + + @Test + void transferAmount_toNonExistentUser_shouldThrowException() { + BigDecimal transferAmount = new BigDecimal("100.00"); + when(accountRepository.findById(1L)).thenReturn(Optional.of(testAccount)); + when(accountRepository.findByUsername("nonexistent")).thenReturn(Optional.empty()); + + RuntimeException exception = assertThrows(RuntimeException.class, + () -> accountService.transferAmount(testAccount, "nonexistent", transferAmount)); + + assertEquals("Recipient account not found", exception.getMessage()); + } + + @Test + void registerAccount_shouldCreateAccountWithZeroBalance() { + when(accountRepository.findByUsername("newuser")).thenReturn(Optional.empty()); + when(passwordEncoder.encode("password")).thenReturn("encodedPassword"); + when(accountRepository.save(any(Account.class))).thenAnswer(i -> { + Account saved = i.getArgument(0); + saved.setId(3L); + return saved; + }); + + Account account = accountService.registerAccount("newuser", "password"); + + assertEquals("newuser", account.getUsername()); + assertEquals(BigDecimal.ZERO, account.getBalance()); + verify(accountRepository).save(any(Account.class)); + } + + @Test + void registerAccount_withDuplicateUsername_shouldThrowException() { + when(accountRepository.findByUsername("testuser")).thenReturn(Optional.of(testAccount)); + + RuntimeException exception = assertThrows(RuntimeException.class, + () -> accountService.registerAccount("testuser", "password")); + + assertEquals("Username already exists", exception.getMessage()); + verify(accountRepository, never()).save(any()); + } + + @Test + void findAccountByUsername_shouldReturnAccount() { + when(accountRepository.findByUsername("testuser")).thenReturn(Optional.of(testAccount)); + + Account found = accountService.findAccountByUsername("testuser"); + + assertEquals("testuser", found.getUsername()); + assertEquals(new BigDecimal("1000.00"), found.getBalance()); + } + + @Test + void findAccountByUsername_notFound_shouldThrowException() { + when(accountRepository.findByUsername("unknown")).thenReturn(Optional.empty()); + + RuntimeException exception = assertThrows(RuntimeException.class, + () -> accountService.findAccountByUsername("unknown")); + + assertEquals("Account not found", exception.getMessage()); + } + + @Test + void getTransactionHistory_shouldReturnTransactions() { + Transaction t1 = new Transaction(); + t1.setId(1L); + Transaction t2 = new Transaction(); + t2.setId(2L); + + when(transactionRepository.findByAccountId(1L)).thenReturn(Arrays.asList(t1, t2)); + + List history = accountService.getTransactionHistory(testAccount); + + assertEquals(2, history.size()); + verify(transactionRepository).findByAccountId(1L); + } + + @Test + void getTransactionHistory_noTransactions_shouldReturnEmptyList() { + when(transactionRepository.findByAccountId(1L)).thenReturn(Collections.emptyList()); + + List history = accountService.getTransactionHistory(testAccount); + + assertTrue(history.isEmpty()); + } + + @Test + void loadUserByUsername_shouldReturnUserDetails() { + when(accountRepository.findByUsername("testuser")).thenReturn(Optional.of(testAccount)); + + var userDetails = accountService.loadUserByUsername("testuser"); + + assertEquals("testuser", userDetails.getUsername()); + assertEquals("encodedPassword", userDetails.getPassword()); + } +} diff --git a/src/test/java/com/example/bankapp/service/TransactionLoggingServiceTest.java b/src/test/java/com/example/bankapp/service/TransactionLoggingServiceTest.java new file mode 100644 index 00000000..0bcbeb24 --- /dev/null +++ b/src/test/java/com/example/bankapp/service/TransactionLoggingServiceTest.java @@ -0,0 +1,103 @@ +package com.example.bankapp.service; + +import com.example.bankapp.model.Account; +import com.example.bankapp.model.Transaction; +import com.example.bankapp.model.TransactionStatus; +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.crypto.password.PasswordEncoder; +import org.springframework.test.context.ActiveProfiles; + +import com.example.bankapp.repository.AccountRepository; + +import java.math.BigDecimal; +import java.util.concurrent.CompletableFuture; + +import static org.junit.jupiter.api.Assertions.*; + +@SpringBootTest +@ActiveProfiles("test") +class TransactionLoggingServiceTest { + + @Autowired + private TransactionLoggingService transactionLoggingService; + + @Autowired + private TransactionRepository transactionRepository; + + @Autowired + private AccountRepository accountRepository; + + @Autowired + private PasswordEncoder passwordEncoder; + + private Account testAccount; + + @BeforeEach + void setUp() { + transactionRepository.deleteAll(); + accountRepository.deleteAll(); + + testAccount = new Account(); + testAccount.setUsername("asynctestuser"); + testAccount.setPassword(passwordEncoder.encode("password")); + testAccount.setBalance(new BigDecimal("1000.00")); + testAccount = accountRepository.save(testAccount); + } + + @Test + void logDepositAsync_shouldReturnCompletableFuture() throws Exception { + CompletableFuture future = transactionLoggingService.logDepositAsync( + testAccount, new BigDecimal("100.00")); + + Transaction result = future.get(); + + assertNotNull(result); + assertNotNull(result.getId()); + assertEquals("Deposit", result.getType()); + assertEquals(new BigDecimal("100.00"), result.getAmount()); + assertEquals(TransactionStatus.COMPLETED, result.getStatus()); + } + + @Test + void logWithdrawalAsync_shouldPersistTransaction() throws Exception { + CompletableFuture future = transactionLoggingService.logWithdrawalAsync( + testAccount, new BigDecimal("50.00")); + + Transaction result = future.get(); + + assertNotNull(result); + assertEquals("Withdrawal", result.getType()); + assertEquals(new BigDecimal("50.00"), result.getAmount()); + assertEquals(TransactionStatus.COMPLETED, result.getStatus()); + } + + @Test + void logTransferAsync_shouldPersistWithCorrectType() throws Exception { + CompletableFuture future = transactionLoggingService.logTransferAsync( + testAccount, new BigDecimal("200.00"), "Transfer Out to recipient"); + + Transaction result = future.get(); + + assertNotNull(result); + assertEquals("Transfer Out to recipient", result.getType()); + assertEquals(new BigDecimal("200.00"), result.getAmount()); + assertEquals(TransactionStatus.COMPLETED, result.getStatus()); + } + + @Test + void logDepositAsync_shouldExecuteOnDifferentThread() throws Exception { + String callerThread = Thread.currentThread().getName(); + + CompletableFuture future = transactionLoggingService.logDepositAsync( + testAccount, new BigDecimal("100.00")); + + future.get(); + + assertNotEquals(callerThread, "payment-async-", + "Async method should run on a payment-async thread, not the caller thread"); + } +} diff --git a/src/test/java/com/example/bankapp/service/TransferTransactionalTest.java b/src/test/java/com/example/bankapp/service/TransferTransactionalTest.java new file mode 100644 index 00000000..c12f36d6 --- /dev/null +++ b/src/test/java/com/example/bankapp/service/TransferTransactionalTest.java @@ -0,0 +1,150 @@ +package com.example.bankapp.service; + +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.context.SpringBootTest; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; + +import static org.junit.jupiter.api.Assertions.*; + +@SpringBootTest +@ActiveProfiles("test") +class TransferTransactionalTest { + + @Autowired + private AccountService accountService; + + @Autowired + private AccountRepository accountRepository; + + @Autowired + private TransactionRepository transactionRepository; + + @Autowired + private PasswordEncoder passwordEncoder; + + @BeforeEach + void setUp() { + transactionRepository.deleteAll(); + accountRepository.deleteAll(); + } + + @Test + @Transactional + void transfer_shouldBeAtomic_bothAccountsUpdated() { + Account sender = new Account(); + sender.setUsername("sender"); + sender.setPassword(passwordEncoder.encode("password")); + sender.setBalance(new BigDecimal("1000.00")); + sender = accountRepository.save(sender); + + Account recipient = new Account(); + recipient.setUsername("recipient"); + recipient.setPassword(passwordEncoder.encode("password")); + recipient.setBalance(new BigDecimal("500.00")); + recipient = accountRepository.save(recipient); + + accountService.transferAmount(sender, "recipient", new BigDecimal("300.00")); + + Account updatedSender = accountRepository.findByUsername("sender").orElseThrow(); + Account updatedRecipient = accountRepository.findByUsername("recipient").orElseThrow(); + + assertEquals(0, updatedSender.getBalance().compareTo(new BigDecimal("700.00"))); + assertEquals(0, updatedRecipient.getBalance().compareTo(new BigDecimal("800.00"))); + } + + @Test + void transfer_withInsufficientFunds_shouldNotChangeAnyBalance() { + Account sender = new Account(); + sender.setUsername("sender2"); + sender.setPassword(passwordEncoder.encode("password")); + sender.setBalance(new BigDecimal("100.00")); + sender = accountRepository.save(sender); + + Account recipient = new Account(); + recipient.setUsername("recipient2"); + recipient.setPassword(passwordEncoder.encode("password")); + recipient.setBalance(new BigDecimal("500.00")); + recipient = accountRepository.save(recipient); + + final Account finalSender = sender; + assertThrows(RuntimeException.class, + () -> accountService.transferAmount(finalSender, "recipient2", new BigDecimal("200.00"))); + + Account unchangedSender = accountRepository.findByUsername("sender2").orElseThrow(); + Account unchangedRecipient = accountRepository.findByUsername("recipient2").orElseThrow(); + + assertEquals(0, unchangedSender.getBalance().compareTo(new BigDecimal("100.00"))); + assertEquals(0, unchangedRecipient.getBalance().compareTo(new BigDecimal("500.00"))); + } + + @Test + void transfer_toNonExistentRecipient_shouldNotDebitSender() { + Account sender = new Account(); + sender.setUsername("sender3"); + sender.setPassword(passwordEncoder.encode("password")); + sender.setBalance(new BigDecimal("1000.00")); + sender = accountRepository.save(sender); + + final Account finalSender = sender; + assertThrows(RuntimeException.class, + () -> accountService.transferAmount(finalSender, "ghost", new BigDecimal("100.00"))); + + Account unchangedSender = accountRepository.findByUsername("sender3").orElseThrow(); + assertEquals(0, unchangedSender.getBalance().compareTo(new BigDecimal("1000.00"))); + } + + @Test + @Transactional + void deposit_followedByWithdraw_shouldReflectCorrectBalance() { + Account account = new Account(); + account.setUsername("balanceuser"); + account.setPassword(passwordEncoder.encode("password")); + account.setBalance(BigDecimal.ZERO); + account = accountRepository.save(account); + + accountService.deposit(account, new BigDecimal("500.00")); + accountService.withdraw(account, new BigDecimal("200.00")); + + Account updated = accountRepository.findByUsername("balanceuser").orElseThrow(); + assertEquals(0, updated.getBalance().compareTo(new BigDecimal("300.00"))); + } + + @Test + void multipleTransfers_shouldMaintainConsistentTotals() { + Account sender = new Account(); + sender.setUsername("multisender"); + sender.setPassword(passwordEncoder.encode("password")); + sender.setBalance(new BigDecimal("1000.00")); + sender = accountRepository.save(sender); + + Account recipient = new Account(); + recipient.setUsername("multirecipient"); + recipient.setPassword(passwordEncoder.encode("password")); + recipient.setBalance(new BigDecimal("0.00")); + recipient = accountRepository.save(recipient); + + for (int i = 0; i < 5; i++) { + sender = accountRepository.findByUsername("multisender").orElseThrow(); + accountService.transferAmount(sender, "multirecipient", new BigDecimal("100.00")); + } + + Account finalSender = accountRepository.findByUsername("multisender").orElseThrow(); + Account finalRecipient = accountRepository.findByUsername("multirecipient").orElseThrow(); + + assertEquals(0, finalSender.getBalance().compareTo(new BigDecimal("500.00"))); + assertEquals(0, finalRecipient.getBalance().compareTo(new BigDecimal("500.00"))); + + BigDecimal total = finalSender.getBalance().add(finalRecipient.getBalance()); + assertEquals(0, total.compareTo(new BigDecimal("1000.00")), + "Total money in the system should remain constant"); + } +} diff --git a/src/test/resources/application-test.properties b/src/test/resources/application-test.properties new file mode 100644 index 00000000..0a4fb1a6 --- /dev/null +++ b/src/test/resources/application-test.properties @@ -0,0 +1,8 @@ +spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect +spring.jpa.show-sql=true