From ddd16fb1b0ee411559e53ee8e45abbb39830fd9e Mon Sep 17 00:00:00 2001 From: roost-io Date: Mon, 23 Mar 2026 04:40:26 +0000 Subject: [PATCH 1/2] Unit test generated by RoostGPT Using AI Model global.anthropic.claude-sonnet-4-20250514-v1:0 --- Online-Banking-App-Spring-Boot/pom.xml | 285 +++++--- .../TransactControllerDepositTest.java | 663 ++++++++++++++++++ 2 files changed, 834 insertions(+), 114 deletions(-) create mode 100644 Online-Banking-App-Spring-Boot/src/test/java/com/beko/DemoBank_v1/controllers/TransactControllerDepositTest.java diff --git a/Online-Banking-App-Spring-Boot/pom.xml b/Online-Banking-App-Spring-Boot/pom.xml index 2f14ebe..fdd1762 100644 --- a/Online-Banking-App-Spring-Boot/pom.xml +++ b/Online-Banking-App-Spring-Boot/pom.xml @@ -1,114 +1,171 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.7.15 - - - com.beko - DemoBank_v1 - 0.0.1-SNAPSHOT - DemoBank_v1 - Demo project for Spring Boot - - 1.8 - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-mail - - - org.springframework.boot - spring-boot-starter-web - - - - com.mysql - mysql-connector-j - runtime - - - - org.springframework.boot - spring-boot-starter-tomcat - provided - - - org.springframework.boot - spring-boot-starter-test - test - - - javax.servlet - javax.servlet-api - 3.1.0 - - - - org.apache.tomcat.embed - tomcat-embed-jasper - provided - - - - org.springframework.boot - spring-boot-starter-validation - - - - javax.servlet.jsp - javax.servlet.jsp-api - 2.3.3 - provided - - - - javax.servlet - jstl - 1.2 - - - - org.springframework.security - spring-security-crypto - - - - io.jsonwebtoken - jjwt-api - 0.11.5 - - - - io.jsonwebtoken - jjwt-impl - 0.11.2 - runtime - - - - io.jsonwebtoken - jjwt-jackson - 0.11.2 - runtime - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.15 + + + + com.beko + DemoBank_v1 + 0.0.1-SNAPSHOT + DemoBank_v1 + Demo project for Spring Boot + + 1.8 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-mail + + + org.springframework.boot + spring-boot-starter-web + + + com.mysql + mysql-connector-j + runtime + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + org.springframework.boot + spring-boot-starter-test + test + + + javax.servlet + javax.servlet-api + 3.1.0 + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + org.springframework.boot + spring-boot-starter-validation + + + javax.servlet.jsp + javax.servlet.jsp-api + 2.3.3 + provided + + + javax.servlet + jstl + 1.2 + + + org.springframework.security + spring-security-crypto + + + io.jsonwebtoken + jjwt-api + 0.11.5 + + + io.jsonwebtoken + jjwt-impl + 0.11.2 + runtime + + + io.jsonwebtoken + jjwt-jackson + 0.11.2 + runtime + + + org.mockito + mockito-junit-jupiter + 2.23.4 + test + + + + io.spring.javaformat + spring-javaformat-formatter + 0.0.40 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.jacoco + jacoco-maven-plugin + 0.8.11 + + + + prepare-agent + + + + report + test + + report + + + coverageReport + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.2.5 + + + + org.apache.maven.plugins + maven-surefire-report-plugin + 3.2.5 + + testReport + + + + + org.apache.maven.plugins + maven-site-plugin + 2.1 + + testReport + + + + + io.spring.javaformat + spring-javaformat-maven-plugin + 0.0.40 + + + + + + + + \ No newline at end of file diff --git a/Online-Banking-App-Spring-Boot/src/test/java/com/beko/DemoBank_v1/controllers/TransactControllerDepositTest.java b/Online-Banking-App-Spring-Boot/src/test/java/com/beko/DemoBank_v1/controllers/TransactControllerDepositTest.java new file mode 100644 index 0000000..526c433 --- /dev/null +++ b/Online-Banking-App-Spring-Boot/src/test/java/com/beko/DemoBank_v1/controllers/TransactControllerDepositTest.java @@ -0,0 +1,663 @@ + +// ********RoostGPT******** +/* +Test generated by RoostGPT for test java-demo_clone using AI Type AWS Bedrock Runtime AI and AI Model global.anthropic.claude-sonnet-4-20250514-v1:0 + +ROOST_METHOD_HASH=deposit_d889dac99b +ROOST_METHOD_SIG_HASH=deposit_54d4c8262f + +Scenario 1: Valid Deposit with Positive Amount + +Details: + TestName: validDepositWithPositiveAmount + Description: This test verifies that a valid deposit request with a positive amount successfully processes the deposit, updates the account balance, logs the transaction, and returns a success response with updated account information. + +Execution: + Arrange: Set up mocked repositories, create a valid User object with user_id, prepare HttpSession with user attribute, create request map with valid deposit_amount and account_id, and mock repository methods to return expected values. + Act: Call the deposit method with the prepared request map and session. + Assert: Verify that the response status is OK (200), response body contains success message, account balance is updated correctly, transaction is logged with correct parameters, and user accounts are returned in response. + +Validation: + This assertion verifies that the core deposit functionality works correctly when provided with valid input parameters. It ensures that the business logic for deposit processing, balance calculation, transaction logging, and response formatting operates as expected in the happy path scenario. + +Scenario 2: Empty Deposit Amount Parameter + +Details: + TestName: emptyDepositAmountParameter + Description: This test ensures that when the deposit_amount parameter is empty or null, the method returns a bad request response with an appropriate error message without processing any deposit operation. + +Execution: + Arrange: Create a request map with empty deposit_amount but valid account_id, set up HttpSession with user attribute, and prepare mocked repositories. + Act: Invoke the deposit method with the request map containing empty deposit_amount. + Assert: Verify that the response status is BAD_REQUEST (400) and the response body contains the error message "Deposit amount and account ID cannot be empty." + +Validation: + This test validates the input validation logic that prevents processing deposits when required parameters are missing. It ensures data integrity and prevents potential null pointer exceptions or invalid operations from occurring downstream in the application flow. + +Scenario 3: Empty Account ID Parameter + +Details: + TestName: emptyAccountIdParameter + Description: This test verifies that when the account_id parameter is empty or null, the method returns a bad request response with an error message, preventing any deposit processing. + +Execution: + Arrange: Prepare a request map with valid deposit_amount but empty account_id, set up HttpSession with user attribute, and configure mocked repositories. + Act: Call the deposit method with the request map containing empty account_id. + Assert: Confirm that the response status is BAD_REQUEST (400) and the response body includes the error message "Deposit amount and account ID cannot be empty." + +Validation: + This assertion ensures that the method properly validates the account_id parameter and prevents deposit operations when the target account cannot be identified. This validation is crucial for maintaining data consistency and preventing deposits to undefined accounts. + +Scenario 4: Both Deposit Amount and Account ID Empty + +Details: + TestName: bothDepositAmountAndAccountIdEmpty + Description: This test checks the behavior when both required parameters (deposit_amount and account_id) are empty, ensuring that the method handles multiple missing parameters correctly. + +Execution: + Arrange: Create a request map with both deposit_amount and account_id as empty strings, prepare HttpSession with user attribute, and set up repository mocks. + Act: Execute the deposit method with the request map containing both empty parameters. + Assert: Verify that the response returns BAD_REQUEST (400) status with the error message "Deposit amount and account ID cannot be empty." + +Validation: + This test confirms that the validation logic correctly handles cases where multiple required parameters are missing simultaneously. It ensures that the error handling is comprehensive and provides appropriate feedback regardless of which combination of parameters is missing. + +Scenario 5: Zero Deposit Amount Value + +Details: + TestName: zeroDepositAmountValue + Description: This test validates that when the deposit amount is zero, the method rejects the request and returns an appropriate error message, preventing meaningless deposit operations. + +Execution: + Arrange: Set up request map with deposit_amount as "0" and valid account_id, prepare HttpSession with user attribute, and configure repository mocks. + Act: Invoke the deposit method with zero deposit amount. + Assert: Verify that the response status is BAD_REQUEST (400) and contains the error message "Deposit amount cannot be zero." + +Validation: + This assertion ensures that the business logic prevents zero-value deposits, which would be meaningless operations that could clutter transaction logs and confuse users. It validates that only meaningful deposit amounts are processed by the system. + +Scenario 6: Negative Deposit Amount Value + +Details: + TestName: negativeDepositAmountValue + Description: This test examines the system's behavior when a negative deposit amount is provided, which should be handled as an invalid operation since deposits should only accept positive values. + +Execution: + Arrange: Create request map with negative deposit_amount (e.g., "-100.00") and valid account_id, set up HttpSession with user, and prepare repository mocks. + Act: Call the deposit method with the negative deposit amount. + Assert: Verify that the method handles the negative value appropriately, either by converting it to positive or rejecting the request. + +Validation: + This test validates the system's handling of logically invalid deposit amounts. While the current method doesn't explicitly check for negative values, this test would reveal whether additional validation is needed to prevent negative deposits or if the system has implicit handling for such cases. + +Scenario 7: Non-Numeric Deposit Amount + +Details: + TestName: nonNumericDepositAmount + Description: This test verifies how the method handles non-numeric deposit amounts, ensuring proper error handling when invalid data types are provided for numeric operations. + +Execution: + Arrange: Prepare request map with non-numeric deposit_amount (e.g., "abc" or "invalid") and valid account_id, set up HttpSession with user, and configure repository mocks. + Act: Execute the deposit method with non-numeric deposit amount. + Assert: Verify that the method throws NumberFormatException or handles the parsing error gracefully. + +Validation: + This test ensures that the method properly handles data type validation and provides appropriate error responses when users submit invalid numeric data. It validates the robustness of the input parsing logic and error handling mechanisms. + +Scenario 8: Non-Numeric Account ID + +Details: + TestName: nonNumericAccountId + Description: This test checks the method's behavior when a non-numeric account ID is provided, ensuring that parsing errors are handled appropriately. + +Execution: + Arrange: Create request map with valid deposit_amount and non-numeric account_id (e.g., "abc123"), prepare HttpSession with user, and set up repository mocks. + Act: Invoke the deposit method with non-numeric account_id. + Assert: Verify that NumberFormatException is thrown or handled gracefully during account ID parsing. + +Validation: + This assertion validates that the method includes proper error handling for invalid account ID formats. It ensures that the system can gracefully handle user input errors and provide meaningful feedback when account identifiers are malformed. + +Scenario 9: Missing User in Session + +Details: + TestName: missingUserInSession + Description: This test validates the method's behavior when no user is stored in the HTTP session, which should prevent any deposit operation from proceeding. + +Execution: + Arrange: Set up request map with valid parameters, create HttpSession without user attribute (returns null), and prepare repository mocks. + Act: Call the deposit method with session containing no user information. + Assert: Verify that NullPointerException is thrown when accessing user.getUser_id() or that the method handles missing user gracefully. + +Validation: + This test ensures that the method includes proper session validation and user authentication checks. It validates that unauthorized or unauthenticated requests are properly rejected, maintaining security and data integrity. + +Scenario 10: Invalid User ID Format in Session + +Details: + TestName: invalidUserIdFormatInSession + Description: This test examines the method's behavior when the user object in the session contains a non-numeric user_id, testing the robustness of user ID parsing. + +Execution: + Arrange: Create User object with non-numeric user_id, store in HttpSession, prepare request map with valid parameters, and set up repository mocks. + Act: Execute the deposit method with invalid user_id format in session. + Assert: Verify that NumberFormatException is thrown during user_id parsing or that appropriate error handling occurs. + +Validation: + This assertion validates that the method properly handles corrupted or invalid session data. It ensures that the system can detect and respond appropriately to data integrity issues in user session information. + +Scenario 11: Account Repository Returns Zero Balance + +Details: + TestName: accountRepositoryReturnsZeroBalance + Description: This test verifies that deposits work correctly when the account has a zero balance, ensuring that the balance calculation and update operations function properly with minimal starting values. + +Execution: + Arrange: Mock accountRepository.getAccountBalance to return 0.0, set up valid request parameters and user session, and configure other repository methods. + Act: Invoke the deposit method with valid parameters on zero-balance account. + Assert: Verify that the new balance equals the deposit amount, transaction is logged correctly, and response contains success message. + +Validation: + This test ensures that the deposit functionality works correctly for accounts with zero balances, which is a common scenario for new accounts or accounts that have been fully withdrawn. It validates the arithmetic operations and state transitions in edge balance conditions. + +Scenario 12: Large Deposit Amount + +Details: + TestName: largeDepositAmount + Description: This test validates the system's handling of very large deposit amounts, ensuring that the method can process high-value transactions without overflow or precision issues. + +Execution: + Arrange: Create request map with very large deposit amount (e.g., "999999999.99"), set up valid user session and account_id, mock repository to return appropriate balance. + Act: Call the deposit method with the large deposit amount. + Assert: Verify that the deposit processes correctly, balance calculation is accurate, and no overflow errors occur. + +Validation: + This assertion ensures that the system can handle high-value transactions that might be common in business or institutional banking scenarios. It validates the numeric precision and range handling capabilities of the deposit processing logic. + +Scenario 13: Decimal Deposit Amount with High Precision + +Details: + TestName: decimalDepositAmountWithHighPrecision + Description: This test checks how the method handles deposit amounts with many decimal places, ensuring proper precision handling in financial calculations. + +Execution: + Arrange: Prepare request map with high-precision decimal deposit_amount (e.g., "123.456789"), set up valid session and account parameters, and configure repository mocks. + Act: Execute the deposit method with high-precision decimal amount. + Assert: Verify that the decimal precision is maintained correctly in balance calculations and that no rounding errors affect the result. + +Validation: + This test validates the financial precision requirements of the banking application. It ensures that deposit amounts are handled with appropriate decimal precision to maintain accuracy in monetary calculations and prevent cumulative rounding errors. + +Scenario 14: Repository Method Failure During Balance Retrieval + +Details: + TestName: repositoryFailureDuringBalanceRetrieval + Description: This test examines the method's behavior when the accountRepository.getAccountBalance method fails or throws an exception, testing error resilience. + +Execution: + Arrange: Mock accountRepository.getAccountBalance to throw RuntimeException, set up valid request parameters and user session, and prepare other repository methods. + Act: Invoke the deposit method when balance retrieval fails. + Assert: Verify that the exception is properly handled or propagated, and that no partial deposit processing occurs. + +Validation: + This assertion ensures that the method includes proper error handling for database or repository failures. It validates that the system maintains data consistency even when underlying data access operations fail unexpectedly. + +Scenario 15: Repository Method Failure During Balance Update + +Details: + TestName: repositoryFailureDuringBalanceUpdate + Description: This test validates the method's behavior when the accountRepository.changeAccountsBalanceById method fails, ensuring proper error handling during the critical balance update operation. + +Execution: + Arrange: Mock accountRepository.changeAccountsBalanceById to throw RuntimeException, set up valid parameters and successful balance retrieval, and configure other repository methods. + Act: Call the deposit method when balance update fails. + Assert: Verify that the failure is handled appropriately and that no inconsistent state is left in the system. + +Validation: + This test ensures that balance update failures are properly managed to prevent data inconsistency. It validates that the method includes appropriate error handling for the most critical operation in the deposit process. + +Scenario 16: Transaction Logging Failure + +Details: + TestName: transactionLoggingFailure + Description: This test checks the method's behavior when the transactRepository.logTransaction method fails, ensuring that transaction logging errors don't prevent successful deposit completion. + +Execution: + Arrange: Mock transactRepository.logTransaction to throw RuntimeException, set up successful balance operations, and prepare valid request parameters. + Act: Execute the deposit method when transaction logging fails. + Assert: Verify that the deposit still completes successfully even if logging fails, or that appropriate error handling occurs. + +Validation: + This assertion validates the error handling priority in the deposit process. It ensures that audit logging failures don't prevent successful financial transactions while still maintaining appropriate error reporting for logging issues. + +Scenario 17: Account Retrieval Failure for Response + +Details: + TestName: accountRetrievalFailureForResponse + Description: This test examines what happens when accountRepository.getUserAccountsById fails during response preparation, after the deposit has been successfully processed. + +Execution: + Arrange: Mock accountRepository.getUserAccountsById to throw RuntimeException, set up successful deposit processing operations, and prepare valid parameters. + Act: Invoke the deposit method when account retrieval for response fails. + Assert: Verify that the deposit operation completes but the response handling addresses the account retrieval failure appropriately. + +Validation: + This test ensures that failures in non-critical operations (like response preparation) don't affect the core deposit functionality. It validates the robustness of the response generation logic and error isolation. + +Scenario 18: Successful Deposit with Existing Balance + +Details: + TestName: successfulDepositWithExistingBalance + Description: This test validates a complete successful deposit scenario where the account has an existing balance, ensuring proper balance addition and comprehensive response generation. + +Execution: + Arrange: Mock accountRepository.getAccountBalance to return 500.0, set up request with deposit_amount "250.0" and valid account_id, prepare user session, and configure all repository methods for success. + Act: Call the deposit method with all valid parameters and existing account balance. + Assert: Verify that the new balance is 750.0, success message is returned, transaction is logged with correct parameters, and user accounts are included in response. + +Validation: + This comprehensive test validates the complete deposit workflow in a realistic scenario with existing account balance. It ensures that all components work together correctly and that the response includes all expected information for a successful deposit operation. + +*/ + +// ********RoostGPT******** +package com.beko.DemoBank_v1.controllers; + +import com.beko.DemoBank_v1.models.User; +import com.beko.DemoBank_v1.repository.AccountRepository; +import com.beko.DemoBank_v1.repository.TransactRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +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.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import javax.servlet.http.HttpSession; +import java.time.LocalDateTime; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; +import org.junit.jupiter.api.*; +import com.beko.DemoBank_v1.models.PaymentRequest; +import com.beko.DemoBank_v1.models.TransferRequest; +import com.beko.DemoBank_v1.repository.PaymentRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import javax.servlet.http.HttpServletRequest; + +@ExtendWith(MockitoExtension.class) +class TransactControllerDepositTest { + + @Mock + private AccountRepository accountRepository; + + @Mock + private TransactRepository transactRepository; + + @Mock + private HttpSession session; + + @InjectMocks + private TransactController transactController; + + private User user; + + private Map requestMap; + + private List mockAccounts; + + @BeforeEach + void setUp() { + user = new User(); + user.setUser_id("123"); + requestMap = new HashMap<>(); + mockAccounts = List.of("Account1", "Account2"); + } + + @Test + @Tag("valid") + void validDepositWithPositiveAmount() { + // Arrange + requestMap.put("deposit_amount", "100.0"); + requestMap.put("account_id", "456"); + + when(session.getAttribute("user")).thenReturn(user); + when(accountRepository.getAccountBalance(123, 456)).thenReturn(500.0); + when(accountRepository.getUserAccountsById(123)).thenReturn((List) mockAccounts); + // Act + ResponseEntity result = transactController.deposit(requestMap, session); + // Assert + assertEquals(HttpStatus.OK, result.getStatusCode()); + Map responseBody = (Map) result.getBody(); + assertEquals("Amount Deposited Successfully.", responseBody.get("message")); + assertEquals(mockAccounts, responseBody.get("accounts")); + + verify(accountRepository).changeAccountsBalanceById(600.0, 456); + verify(transactRepository).logTransaction(eq(456), eq("deposit"), eq(100.0), eq("online"), eq("success"), + eq("Deposit Transaction Successfull"), any(LocalDateTime.class)); + } + + @Test + @Tag("invalid") + void emptyDepositAmountParameter() { + // Arrange + requestMap.put("deposit_amount", ""); + requestMap.put("account_id", "456"); + // Act + ResponseEntity result = transactController.deposit(requestMap, session); + // Assert + assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode()); + assertEquals("Deposit amount and account ID cannot be empty.", result.getBody()); + + verifyNoInteractions(accountRepository, transactRepository); + } + + @Test + @Tag("invalid") + void emptyAccountIdParameter() { + // Arrange + requestMap.put("deposit_amount", "100.0"); + requestMap.put("account_id", ""); + // Act + ResponseEntity result = transactController.deposit(requestMap, session); + // Assert + assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode()); + assertEquals("Deposit amount and account ID cannot be empty.", result.getBody()); + + verifyNoInteractions(accountRepository, transactRepository); + } + + @Test + @Tag("invalid") + void bothDepositAmountAndAccountIdEmpty() { + // Arrange + requestMap.put("deposit_amount", ""); + requestMap.put("account_id", ""); + // Act + ResponseEntity result = transactController.deposit(requestMap, session); + // Assert + assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode()); + assertEquals("Deposit amount and account ID cannot be empty.", result.getBody()); + + verifyNoInteractions(accountRepository, transactRepository); + } + + @Test + @Tag("boundary") + void zeroDepositAmountValue() { + // Arrange + requestMap.put("deposit_amount", "0"); + requestMap.put("account_id", "456"); + + when(session.getAttribute("user")).thenReturn(user); + // Act + ResponseEntity result = transactController.deposit(requestMap, session); + // Assert + assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode()); + assertEquals("Deposit amount cannot be zero.", result.getBody()); + + verify(accountRepository, never()).changeAccountsBalanceById(anyDouble(), anyInt()); + verify(transactRepository, never()).logTransaction(anyInt(), anyString(), anyDouble(), anyString(), anyString(), + anyString(), any(LocalDateTime.class)); + } + + @Test + @Tag("boundary") + void negativeDepositAmountValue() { + // Arrange + requestMap.put("deposit_amount", "-100.0"); + requestMap.put("account_id", "456"); + + when(session.getAttribute("user")).thenReturn(user); + when(accountRepository.getAccountBalance(123, 456)).thenReturn(500.0); + when(accountRepository.getUserAccountsById(123)).thenReturn((List) mockAccounts); + // Act + ResponseEntity result = transactController.deposit(requestMap, session); + // Assert + assertEquals(HttpStatus.OK, result.getStatusCode()); + Map responseBody = (Map) result.getBody(); + assertEquals("Amount Deposited Successfully.", responseBody.get("message")); + + verify(accountRepository).changeAccountsBalanceById(400.0, 456); + verify(transactRepository).logTransaction(eq(456), eq("deposit"), eq(-100.0), eq("online"), eq("success"), + eq("Deposit Transaction Successfull"), any(LocalDateTime.class)); + } + + @Test + @Tag("invalid") + void nonNumericDepositAmount() { + // Arrange + requestMap.put("deposit_amount", "abc"); + requestMap.put("account_id", "456"); + + when(session.getAttribute("user")).thenReturn(user); + // Act & Assert + assertThrows(NumberFormatException.class, () -> { + transactController.deposit(requestMap, session); + }); + } + + @Test + @Tag("invalid") + void nonNumericAccountId() { + // Arrange + requestMap.put("deposit_amount", "100.0"); + requestMap.put("account_id", "abc123"); + + when(session.getAttribute("user")).thenReturn(user); + // Act & Assert + assertThrows(NumberFormatException.class, () -> { + transactController.deposit(requestMap, session); + }); + } + + @Test + @Tag("invalid") + void missingUserInSession() { + // Arrange + requestMap.put("deposit_amount", "100.0"); + requestMap.put("account_id", "456"); + + when(session.getAttribute("user")).thenReturn(null); + // Act & Assert + assertThrows(NullPointerException.class, () -> { + transactController.deposit(requestMap, session); + }); + } + + @Test + @Tag("invalid") + void invalidUserIdFormatInSession() { + // Arrange + requestMap.put("deposit_amount", "100.0"); + requestMap.put("account_id", "456"); + + User invalidUser = new User(); + invalidUser.setUser_id("invalid_id"); + when(session.getAttribute("user")).thenReturn(invalidUser); + // Act & Assert + assertThrows(NumberFormatException.class, () -> { + transactController.deposit(requestMap, session); + }); + } + + @Test + @Tag("boundary") + void accountRepositoryReturnsZeroBalance() { + // Arrange + requestMap.put("deposit_amount", "250.0"); + requestMap.put("account_id", "456"); + + when(session.getAttribute("user")).thenReturn(user); + when(accountRepository.getAccountBalance(123, 456)).thenReturn(0.0); + when(accountRepository.getUserAccountsById(123)).thenReturn((List) mockAccounts); + // Act + ResponseEntity result = transactController.deposit(requestMap, session); + // Assert + assertEquals(HttpStatus.OK, result.getStatusCode()); + Map responseBody = (Map) result.getBody(); + assertEquals("Amount Deposited Successfully.", responseBody.get("message")); + + verify(accountRepository).changeAccountsBalanceById(250.0, 456); + verify(transactRepository).logTransaction(eq(456), eq("deposit"), eq(250.0), eq("online"), eq("success"), + eq("Deposit Transaction Successfull"), any(LocalDateTime.class)); + } + + @Test + @Tag("boundary") + void largeDepositAmount() { + // Arrange + requestMap.put("deposit_amount", "999999999.99"); + requestMap.put("account_id", "456"); + + when(session.getAttribute("user")).thenReturn(user); + when(accountRepository.getAccountBalance(123, 456)).thenReturn(1000.0); + when(accountRepository.getUserAccountsById(123)).thenReturn((List) mockAccounts); + // Act + ResponseEntity result = transactController.deposit(requestMap, session); + // Assert + assertEquals(HttpStatus.OK, result.getStatusCode()); + Map responseBody = (Map) result.getBody(); + assertEquals("Amount Deposited Successfully.", responseBody.get("message")); + + verify(accountRepository).changeAccountsBalanceById(1000000000.99, 456); + verify(transactRepository).logTransaction(eq(456), eq("deposit"), eq(999999999.99), eq("online"), eq("success"), + eq("Deposit Transaction Successfull"), any(LocalDateTime.class)); + } + + @Test + @Tag("boundary") + void decimalDepositAmountWithHighPrecision() { + // Arrange + requestMap.put("deposit_amount", "123.456789"); + requestMap.put("account_id", "456"); + + when(session.getAttribute("user")).thenReturn(user); + when(accountRepository.getAccountBalance(123, 456)).thenReturn(500.0); + when(accountRepository.getUserAccountsById(123)).thenReturn((List) mockAccounts); + // Act + ResponseEntity result = transactController.deposit(requestMap, session); + // Assert + assertEquals(HttpStatus.OK, result.getStatusCode()); + Map responseBody = (Map) result.getBody(); + assertEquals("Amount Deposited Successfully.", responseBody.get("message")); + + verify(accountRepository).changeAccountsBalanceById(623.456789, 456); + verify(transactRepository).logTransaction(eq(456), eq("deposit"), eq(123.456789), eq("online"), eq("success"), + eq("Deposit Transaction Successfull"), any(LocalDateTime.class)); + } + + @Test + @Tag("integration") + void repositoryFailureDuringBalanceRetrieval() { + // Arrange + requestMap.put("deposit_amount", "100.0"); + requestMap.put("account_id", "456"); + + when(session.getAttribute("user")).thenReturn(user); + when(accountRepository.getAccountBalance(123, 456)).thenThrow(new RuntimeException("Database error")); + // Act & Assert + assertThrows(RuntimeException.class, () -> { + transactController.deposit(requestMap, session); + }); + + verify(accountRepository, never()).changeAccountsBalanceById(anyDouble(), anyInt()); + verify(transactRepository, never()).logTransaction(anyInt(), anyString(), anyDouble(), anyString(), anyString(), + anyString(), any(LocalDateTime.class)); + } + + @Test + @Tag("integration") + void repositoryFailureDuringBalanceUpdate() { + // Arrange + requestMap.put("deposit_amount", "100.0"); + requestMap.put("account_id", "456"); + + when(session.getAttribute("user")).thenReturn(user); + when(accountRepository.getAccountBalance(123, 456)).thenReturn(500.0); + doThrow(new RuntimeException("Update failed")).when(accountRepository).changeAccountsBalanceById(600.0, 456); + // Act & Assert + assertThrows(RuntimeException.class, () -> { + transactController.deposit(requestMap, session); + }); + + verify(transactRepository, never()).logTransaction(anyInt(), anyString(), anyDouble(), anyString(), anyString(), + anyString(), any(LocalDateTime.class)); + } + + @Test + @Tag("integration") + void transactionLoggingFailure() { + // Arrange + requestMap.put("deposit_amount", "100.0"); + requestMap.put("account_id", "456"); + + when(session.getAttribute("user")).thenReturn(user); + when(accountRepository.getAccountBalance(123, 456)).thenReturn(500.0); + doThrow(new RuntimeException("Logging failed")).when(transactRepository) + .logTransaction(anyInt(), anyString(), anyDouble(), anyString(), anyString(), anyString(), + any(LocalDateTime.class)); + // Act & Assert + assertThrows(RuntimeException.class, () -> { + transactController.deposit(requestMap, session); + }); + + verify(accountRepository).changeAccountsBalanceById(600.0, 456); + } + + @Test + @Tag("integration") + void accountRetrievalFailureForResponse() { + // Arrange + requestMap.put("deposit_amount", "100.0"); + requestMap.put("account_id", "456"); + + when(session.getAttribute("user")).thenReturn(user); + when(accountRepository.getAccountBalance(123, 456)).thenReturn(500.0); + when(accountRepository.getUserAccountsById(123)).thenThrow(new RuntimeException("Account retrieval failed")); + // Act & Assert + assertThrows(RuntimeException.class, () -> { + transactController.deposit(requestMap, session); + }); + + verify(accountRepository).changeAccountsBalanceById(600.0, 456); + verify(transactRepository).logTransaction(eq(456), eq("deposit"), eq(100.0), eq("online"), eq("success"), + eq("Deposit Transaction Successfull"), any(LocalDateTime.class)); + } + + @Test + @Tag("valid") + void successfulDepositWithExistingBalance() { + // Arrange + requestMap.put("deposit_amount", "250.0"); + requestMap.put("account_id", "456"); + + when(session.getAttribute("user")).thenReturn(user); + when(accountRepository.getAccountBalance(123, 456)).thenReturn(500.0); + when(accountRepository.getUserAccountsById(123)).thenReturn((List) mockAccounts); + // Act + ResponseEntity result = transactController.deposit(requestMap, session); + // Assert + assertEquals(HttpStatus.OK, result.getStatusCode()); + Map responseBody = (Map) result.getBody(); + assertNotNull(responseBody); + assertEquals("Amount Deposited Successfully.", responseBody.get("message")); + assertEquals(mockAccounts, responseBody.get("accounts")); + + verify(accountRepository).getAccountBalance(123, 456); + verify(accountRepository).changeAccountsBalanceById(750.0, 456); + verify(transactRepository).logTransaction(eq(456), eq("deposit"), eq(250.0), eq("online"), eq("success"), + eq("Deposit Transaction Successfull"), any(LocalDateTime.class)); + verify(accountRepository).getUserAccountsById(123); + } + +} \ No newline at end of file From 529388565a1ad3d6f0156b0f327cb8217e5ec5dc Mon Sep 17 00:00:00 2001 From: roost-io Date: Mon, 23 Mar 2026 04:45:23 +0000 Subject: [PATCH 2/2] Improved Unit test generated by RoostGPT Using AI Model global.anthropic.claude-sonnet-4-20250514-v1:0, for user feedback: -\sImprove\svariable\snames --- .../TransactControllerDepositTest.java | 401 +++++++++--------- 1 file changed, 193 insertions(+), 208 deletions(-) mode change 100644 => 100755 Online-Banking-App-Spring-Boot/src/test/java/com/beko/DemoBank_v1/controllers/TransactControllerDepositTest.java diff --git a/Online-Banking-App-Spring-Boot/src/test/java/com/beko/DemoBank_v1/controllers/TransactControllerDepositTest.java b/Online-Banking-App-Spring-Boot/src/test/java/com/beko/DemoBank_v1/controllers/TransactControllerDepositTest.java old mode 100644 new mode 100755 index 526c433..6003e2d --- a/Online-Banking-App-Spring-Boot/src/test/java/com/beko/DemoBank_v1/controllers/TransactControllerDepositTest.java +++ b/Online-Banking-App-Spring-Boot/src/test/java/com/beko/DemoBank_v1/controllers/TransactControllerDepositTest.java @@ -258,9 +258,12 @@ Validation: This comprehensive test validates the complete deposit workflow in a realistic scenario with existing account balance. It ensures that all components work together correctly and that the response includes all expected information for a successful deposit operation. + +roost_feedback [23/03/2026, 4:42:56 AM]:-\sImprove\svariable\snames */ // ********RoostGPT******** + package com.beko.DemoBank_v1.controllers; import com.beko.DemoBank_v1.models.User; @@ -298,366 +301,348 @@ class TransactControllerDepositTest { @Mock - private AccountRepository accountRepository; + private AccountRepository mockAccountRepository; @Mock - private TransactRepository transactRepository; + private TransactRepository mockTransactRepository; @Mock - private HttpSession session; + private HttpSession mockHttpSession; @InjectMocks private TransactController transactController; - private User user; + private User testUser; - private Map requestMap; + private Map depositRequestMap; - private List mockAccounts; + private List mockUserAccounts; @BeforeEach void setUp() { - user = new User(); - user.setUser_id("123"); - requestMap = new HashMap<>(); - mockAccounts = List.of("Account1", "Account2"); + testUser = new User(); + testUser.setUser_id("123"); + depositRequestMap = new HashMap<>(); + mockUserAccounts = List.of("Account1", "Account2"); } @Test @Tag("valid") void validDepositWithPositiveAmount() { - // Arrange - requestMap.put("deposit_amount", "100.0"); - requestMap.put("account_id", "456"); - - when(session.getAttribute("user")).thenReturn(user); - when(accountRepository.getAccountBalance(123, 456)).thenReturn(500.0); - when(accountRepository.getUserAccountsById(123)).thenReturn((List) mockAccounts); - // Act - ResponseEntity result = transactController.deposit(requestMap, session); - // Assert - assertEquals(HttpStatus.OK, result.getStatusCode()); - Map responseBody = (Map) result.getBody(); + depositRequestMap.put("deposit_amount", "100.0"); + depositRequestMap.put("account_id", "456"); + + when(mockHttpSession.getAttribute("user")).thenReturn(testUser); + when(mockAccountRepository.getAccountBalance(123, 456)).thenReturn(500.0); + when(mockAccountRepository.getUserAccountsById(123)).thenReturn((List) mockUserAccounts); + + ResponseEntity actualResponse = transactController.deposit(depositRequestMap, mockHttpSession); + + assertEquals(HttpStatus.OK, actualResponse.getStatusCode()); + Map responseBody = (Map) actualResponse.getBody(); assertEquals("Amount Deposited Successfully.", responseBody.get("message")); - assertEquals(mockAccounts, responseBody.get("accounts")); + assertEquals(mockUserAccounts, responseBody.get("accounts")); - verify(accountRepository).changeAccountsBalanceById(600.0, 456); - verify(transactRepository).logTransaction(eq(456), eq("deposit"), eq(100.0), eq("online"), eq("success"), + verify(mockAccountRepository).changeAccountsBalanceById(600.0, 456); + verify(mockTransactRepository).logTransaction(eq(456), eq("deposit"), eq(100.0), eq("online"), eq("success"), eq("Deposit Transaction Successfull"), any(LocalDateTime.class)); } @Test @Tag("invalid") void emptyDepositAmountParameter() { - // Arrange - requestMap.put("deposit_amount", ""); - requestMap.put("account_id", "456"); - // Act - ResponseEntity result = transactController.deposit(requestMap, session); - // Assert - assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode()); - assertEquals("Deposit amount and account ID cannot be empty.", result.getBody()); - - verifyNoInteractions(accountRepository, transactRepository); + depositRequestMap.put("deposit_amount", ""); + depositRequestMap.put("account_id", "456"); + + ResponseEntity actualResponse = transactController.deposit(depositRequestMap, mockHttpSession); + + assertEquals(HttpStatus.BAD_REQUEST, actualResponse.getStatusCode()); + assertEquals("Deposit amount and account ID cannot be empty.", actualResponse.getBody()); + + verifyNoInteractions(mockAccountRepository, mockTransactRepository); } @Test @Tag("invalid") void emptyAccountIdParameter() { - // Arrange - requestMap.put("deposit_amount", "100.0"); - requestMap.put("account_id", ""); - // Act - ResponseEntity result = transactController.deposit(requestMap, session); - // Assert - assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode()); - assertEquals("Deposit amount and account ID cannot be empty.", result.getBody()); - - verifyNoInteractions(accountRepository, transactRepository); + depositRequestMap.put("deposit_amount", "100.0"); + depositRequestMap.put("account_id", ""); + + ResponseEntity actualResponse = transactController.deposit(depositRequestMap, mockHttpSession); + + assertEquals(HttpStatus.BAD_REQUEST, actualResponse.getStatusCode()); + assertEquals("Deposit amount and account ID cannot be empty.", actualResponse.getBody()); + + verifyNoInteractions(mockAccountRepository, mockTransactRepository); } @Test @Tag("invalid") void bothDepositAmountAndAccountIdEmpty() { - // Arrange - requestMap.put("deposit_amount", ""); - requestMap.put("account_id", ""); - // Act - ResponseEntity result = transactController.deposit(requestMap, session); - // Assert - assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode()); - assertEquals("Deposit amount and account ID cannot be empty.", result.getBody()); - - verifyNoInteractions(accountRepository, transactRepository); + depositRequestMap.put("deposit_amount", ""); + depositRequestMap.put("account_id", ""); + + ResponseEntity actualResponse = transactController.deposit(depositRequestMap, mockHttpSession); + + assertEquals(HttpStatus.BAD_REQUEST, actualResponse.getStatusCode()); + assertEquals("Deposit amount and account ID cannot be empty.", actualResponse.getBody()); + + verifyNoInteractions(mockAccountRepository, mockTransactRepository); } @Test @Tag("boundary") void zeroDepositAmountValue() { - // Arrange - requestMap.put("deposit_amount", "0"); - requestMap.put("account_id", "456"); - - when(session.getAttribute("user")).thenReturn(user); - // Act - ResponseEntity result = transactController.deposit(requestMap, session); - // Assert - assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode()); - assertEquals("Deposit amount cannot be zero.", result.getBody()); - - verify(accountRepository, never()).changeAccountsBalanceById(anyDouble(), anyInt()); - verify(transactRepository, never()).logTransaction(anyInt(), anyString(), anyDouble(), anyString(), anyString(), + depositRequestMap.put("deposit_amount", "0"); + depositRequestMap.put("account_id", "456"); + + when(mockHttpSession.getAttribute("user")).thenReturn(testUser); + + ResponseEntity actualResponse = transactController.deposit(depositRequestMap, mockHttpSession); + + assertEquals(HttpStatus.BAD_REQUEST, actualResponse.getStatusCode()); + assertEquals("Deposit amount cannot be zero.", actualResponse.getBody()); + + verify(mockAccountRepository, never()).changeAccountsBalanceById(anyDouble(), anyInt()); + verify(mockTransactRepository, never()).logTransaction(anyInt(), anyString(), anyDouble(), anyString(), anyString(), anyString(), any(LocalDateTime.class)); } @Test @Tag("boundary") void negativeDepositAmountValue() { - // Arrange - requestMap.put("deposit_amount", "-100.0"); - requestMap.put("account_id", "456"); - - when(session.getAttribute("user")).thenReturn(user); - when(accountRepository.getAccountBalance(123, 456)).thenReturn(500.0); - when(accountRepository.getUserAccountsById(123)).thenReturn((List) mockAccounts); - // Act - ResponseEntity result = transactController.deposit(requestMap, session); - // Assert - assertEquals(HttpStatus.OK, result.getStatusCode()); - Map responseBody = (Map) result.getBody(); + depositRequestMap.put("deposit_amount", "-100.0"); + depositRequestMap.put("account_id", "456"); + + when(mockHttpSession.getAttribute("user")).thenReturn(testUser); + when(mockAccountRepository.getAccountBalance(123, 456)).thenReturn(500.0); + when(mockAccountRepository.getUserAccountsById(123)).thenReturn((List) mockUserAccounts); + + ResponseEntity actualResponse = transactController.deposit(depositRequestMap, mockHttpSession); + + assertEquals(HttpStatus.OK, actualResponse.getStatusCode()); + Map responseBody = (Map) actualResponse.getBody(); assertEquals("Amount Deposited Successfully.", responseBody.get("message")); - verify(accountRepository).changeAccountsBalanceById(400.0, 456); - verify(transactRepository).logTransaction(eq(456), eq("deposit"), eq(-100.0), eq("online"), eq("success"), + verify(mockAccountRepository).changeAccountsBalanceById(400.0, 456); + verify(mockTransactRepository).logTransaction(eq(456), eq("deposit"), eq(-100.0), eq("online"), eq("success"), eq("Deposit Transaction Successfull"), any(LocalDateTime.class)); } @Test @Tag("invalid") void nonNumericDepositAmount() { - // Arrange - requestMap.put("deposit_amount", "abc"); - requestMap.put("account_id", "456"); + depositRequestMap.put("deposit_amount", "abc"); + depositRequestMap.put("account_id", "456"); + + when(mockHttpSession.getAttribute("user")).thenReturn(testUser); - when(session.getAttribute("user")).thenReturn(user); - // Act & Assert assertThrows(NumberFormatException.class, () -> { - transactController.deposit(requestMap, session); + transactController.deposit(depositRequestMap, mockHttpSession); }); } @Test @Tag("invalid") void nonNumericAccountId() { - // Arrange - requestMap.put("deposit_amount", "100.0"); - requestMap.put("account_id", "abc123"); + depositRequestMap.put("deposit_amount", "100.0"); + depositRequestMap.put("account_id", "abc123"); + + when(mockHttpSession.getAttribute("user")).thenReturn(testUser); - when(session.getAttribute("user")).thenReturn(user); - // Act & Assert assertThrows(NumberFormatException.class, () -> { - transactController.deposit(requestMap, session); + transactController.deposit(depositRequestMap, mockHttpSession); }); } @Test @Tag("invalid") void missingUserInSession() { - // Arrange - requestMap.put("deposit_amount", "100.0"); - requestMap.put("account_id", "456"); + depositRequestMap.put("deposit_amount", "100.0"); + depositRequestMap.put("account_id", "456"); + + when(mockHttpSession.getAttribute("user")).thenReturn(null); - when(session.getAttribute("user")).thenReturn(null); - // Act & Assert assertThrows(NullPointerException.class, () -> { - transactController.deposit(requestMap, session); + transactController.deposit(depositRequestMap, mockHttpSession); }); } @Test @Tag("invalid") void invalidUserIdFormatInSession() { - // Arrange - requestMap.put("deposit_amount", "100.0"); - requestMap.put("account_id", "456"); - - User invalidUser = new User(); - invalidUser.setUser_id("invalid_id"); - when(session.getAttribute("user")).thenReturn(invalidUser); - // Act & Assert + depositRequestMap.put("deposit_amount", "100.0"); + depositRequestMap.put("account_id", "456"); + + User userWithInvalidId = new User(); + userWithInvalidId.setUser_id("invalid_id"); + when(mockHttpSession.getAttribute("user")).thenReturn(userWithInvalidId); + assertThrows(NumberFormatException.class, () -> { - transactController.deposit(requestMap, session); + transactController.deposit(depositRequestMap, mockHttpSession); }); } @Test @Tag("boundary") void accountRepositoryReturnsZeroBalance() { - // Arrange - requestMap.put("deposit_amount", "250.0"); - requestMap.put("account_id", "456"); - - when(session.getAttribute("user")).thenReturn(user); - when(accountRepository.getAccountBalance(123, 456)).thenReturn(0.0); - when(accountRepository.getUserAccountsById(123)).thenReturn((List) mockAccounts); - // Act - ResponseEntity result = transactController.deposit(requestMap, session); - // Assert - assertEquals(HttpStatus.OK, result.getStatusCode()); - Map responseBody = (Map) result.getBody(); + depositRequestMap.put("deposit_amount", "250.0"); + depositRequestMap.put("account_id", "456"); + + when(mockHttpSession.getAttribute("user")).thenReturn(testUser); + when(mockAccountRepository.getAccountBalance(123, 456)).thenReturn(0.0); + when(mockAccountRepository.getUserAccountsById(123)).thenReturn((List) mockUserAccounts); + + ResponseEntity actualResponse = transactController.deposit(depositRequestMap, mockHttpSession); + + assertEquals(HttpStatus.OK, actualResponse.getStatusCode()); + Map responseBody = (Map) actualResponse.getBody(); assertEquals("Amount Deposited Successfully.", responseBody.get("message")); - verify(accountRepository).changeAccountsBalanceById(250.0, 456); - verify(transactRepository).logTransaction(eq(456), eq("deposit"), eq(250.0), eq("online"), eq("success"), + verify(mockAccountRepository).changeAccountsBalanceById(250.0, 456); + verify(mockTransactRepository).logTransaction(eq(456), eq("deposit"), eq(250.0), eq("online"), eq("success"), eq("Deposit Transaction Successfull"), any(LocalDateTime.class)); } @Test @Tag("boundary") void largeDepositAmount() { - // Arrange - requestMap.put("deposit_amount", "999999999.99"); - requestMap.put("account_id", "456"); - - when(session.getAttribute("user")).thenReturn(user); - when(accountRepository.getAccountBalance(123, 456)).thenReturn(1000.0); - when(accountRepository.getUserAccountsById(123)).thenReturn((List) mockAccounts); - // Act - ResponseEntity result = transactController.deposit(requestMap, session); - // Assert - assertEquals(HttpStatus.OK, result.getStatusCode()); - Map responseBody = (Map) result.getBody(); + depositRequestMap.put("deposit_amount", "999999999.99"); + depositRequestMap.put("account_id", "456"); + + when(mockHttpSession.getAttribute("user")).thenReturn(testUser); + when(mockAccountRepository.getAccountBalance(123, 456)).thenReturn(1000.0); + when(mockAccountRepository.getUserAccountsById(123)).thenReturn((List) mockUserAccounts); + + ResponseEntity actualResponse = transactController.deposit(depositRequestMap, mockHttpSession); + + assertEquals(HttpStatus.OK, actualResponse.getStatusCode()); + Map responseBody = (Map) actualResponse.getBody(); assertEquals("Amount Deposited Successfully.", responseBody.get("message")); - verify(accountRepository).changeAccountsBalanceById(1000000000.99, 456); - verify(transactRepository).logTransaction(eq(456), eq("deposit"), eq(999999999.99), eq("online"), eq("success"), + verify(mockAccountRepository).changeAccountsBalanceById(1000000000.99, 456); + verify(mockTransactRepository).logTransaction(eq(456), eq("deposit"), eq(999999999.99), eq("online"), eq("success"), eq("Deposit Transaction Successfull"), any(LocalDateTime.class)); } @Test @Tag("boundary") void decimalDepositAmountWithHighPrecision() { - // Arrange - requestMap.put("deposit_amount", "123.456789"); - requestMap.put("account_id", "456"); - - when(session.getAttribute("user")).thenReturn(user); - when(accountRepository.getAccountBalance(123, 456)).thenReturn(500.0); - when(accountRepository.getUserAccountsById(123)).thenReturn((List) mockAccounts); - // Act - ResponseEntity result = transactController.deposit(requestMap, session); - // Assert - assertEquals(HttpStatus.OK, result.getStatusCode()); - Map responseBody = (Map) result.getBody(); + depositRequestMap.put("deposit_amount", "123.456789"); + depositRequestMap.put("account_id", "456"); + + when(mockHttpSession.getAttribute("user")).thenReturn(testUser); + when(mockAccountRepository.getAccountBalance(123, 456)).thenReturn(500.0); + when(mockAccountRepository.getUserAccountsById(123)).thenReturn((List) mockUserAccounts); + + ResponseEntity actualResponse = transactController.deposit(depositRequestMap, mockHttpSession); + + assertEquals(HttpStatus.OK, actualResponse.getStatusCode()); + Map responseBody = (Map) actualResponse.getBody(); assertEquals("Amount Deposited Successfully.", responseBody.get("message")); - verify(accountRepository).changeAccountsBalanceById(623.456789, 456); - verify(transactRepository).logTransaction(eq(456), eq("deposit"), eq(123.456789), eq("online"), eq("success"), + verify(mockAccountRepository).changeAccountsBalanceById(623.456789, 456); + verify(mockTransactRepository).logTransaction(eq(456), eq("deposit"), eq(123.456789), eq("online"), eq("success"), eq("Deposit Transaction Successfull"), any(LocalDateTime.class)); } @Test @Tag("integration") void repositoryFailureDuringBalanceRetrieval() { - // Arrange - requestMap.put("deposit_amount", "100.0"); - requestMap.put("account_id", "456"); + depositRequestMap.put("deposit_amount", "100.0"); + depositRequestMap.put("account_id", "456"); + + when(mockHttpSession.getAttribute("user")).thenReturn(testUser); + when(mockAccountRepository.getAccountBalance(123, 456)).thenThrow(new RuntimeException("Database error")); - when(session.getAttribute("user")).thenReturn(user); - when(accountRepository.getAccountBalance(123, 456)).thenThrow(new RuntimeException("Database error")); - // Act & Assert assertThrows(RuntimeException.class, () -> { - transactController.deposit(requestMap, session); + transactController.deposit(depositRequestMap, mockHttpSession); }); - verify(accountRepository, never()).changeAccountsBalanceById(anyDouble(), anyInt()); - verify(transactRepository, never()).logTransaction(anyInt(), anyString(), anyDouble(), anyString(), anyString(), + verify(mockAccountRepository, never()).changeAccountsBalanceById(anyDouble(), anyInt()); + verify(mockTransactRepository, never()).logTransaction(anyInt(), anyString(), anyDouble(), anyString(), anyString(), anyString(), any(LocalDateTime.class)); } @Test @Tag("integration") void repositoryFailureDuringBalanceUpdate() { - // Arrange - requestMap.put("deposit_amount", "100.0"); - requestMap.put("account_id", "456"); - - when(session.getAttribute("user")).thenReturn(user); - when(accountRepository.getAccountBalance(123, 456)).thenReturn(500.0); - doThrow(new RuntimeException("Update failed")).when(accountRepository).changeAccountsBalanceById(600.0, 456); - // Act & Assert + depositRequestMap.put("deposit_amount", "100.0"); + depositRequestMap.put("account_id", "456"); + + when(mockHttpSession.getAttribute("user")).thenReturn(testUser); + when(mockAccountRepository.getAccountBalance(123, 456)).thenReturn(500.0); + doThrow(new RuntimeException("Update failed")).when(mockAccountRepository).changeAccountsBalanceById(600.0, 456); + assertThrows(RuntimeException.class, () -> { - transactController.deposit(requestMap, session); + transactController.deposit(depositRequestMap, mockHttpSession); }); - verify(transactRepository, never()).logTransaction(anyInt(), anyString(), anyDouble(), anyString(), anyString(), + verify(mockTransactRepository, never()).logTransaction(anyInt(), anyString(), anyDouble(), anyString(), anyString(), anyString(), any(LocalDateTime.class)); } @Test @Tag("integration") void transactionLoggingFailure() { - // Arrange - requestMap.put("deposit_amount", "100.0"); - requestMap.put("account_id", "456"); + depositRequestMap.put("deposit_amount", "100.0"); + depositRequestMap.put("account_id", "456"); - when(session.getAttribute("user")).thenReturn(user); - when(accountRepository.getAccountBalance(123, 456)).thenReturn(500.0); - doThrow(new RuntimeException("Logging failed")).when(transactRepository) + when(mockHttpSession.getAttribute("user")).thenReturn(testUser); + when(mockAccountRepository.getAccountBalance(123, 456)).thenReturn(500.0); + doThrow(new RuntimeException("Logging failed")).when(mockTransactRepository) .logTransaction(anyInt(), anyString(), anyDouble(), anyString(), anyString(), anyString(), any(LocalDateTime.class)); - // Act & Assert + assertThrows(RuntimeException.class, () -> { - transactController.deposit(requestMap, session); + transactController.deposit(depositRequestMap, mockHttpSession); }); - verify(accountRepository).changeAccountsBalanceById(600.0, 456); + verify(mockAccountRepository).changeAccountsBalanceById(600.0, 456); } @Test @Tag("integration") void accountRetrievalFailureForResponse() { - // Arrange - requestMap.put("deposit_amount", "100.0"); - requestMap.put("account_id", "456"); - - when(session.getAttribute("user")).thenReturn(user); - when(accountRepository.getAccountBalance(123, 456)).thenReturn(500.0); - when(accountRepository.getUserAccountsById(123)).thenThrow(new RuntimeException("Account retrieval failed")); - // Act & Assert + depositRequestMap.put("deposit_amount", "100.0"); + depositRequestMap.put("account_id", "456"); + + when(mockHttpSession.getAttribute("user")).thenReturn(testUser); + when(mockAccountRepository.getAccountBalance(123, 456)).thenReturn(500.0); + when(mockAccountRepository.getUserAccountsById(123)).thenThrow(new RuntimeException("Account retrieval failed")); + assertThrows(RuntimeException.class, () -> { - transactController.deposit(requestMap, session); + transactController.deposit(depositRequestMap, mockHttpSession); }); - verify(accountRepository).changeAccountsBalanceById(600.0, 456); - verify(transactRepository).logTransaction(eq(456), eq("deposit"), eq(100.0), eq("online"), eq("success"), + verify(mockAccountRepository).changeAccountsBalanceById(600.0, 456); + verify(mockTransactRepository).logTransaction(eq(456), eq("deposit"), eq(100.0), eq("online"), eq("success"), eq("Deposit Transaction Successfull"), any(LocalDateTime.class)); } @Test @Tag("valid") void successfulDepositWithExistingBalance() { - // Arrange - requestMap.put("deposit_amount", "250.0"); - requestMap.put("account_id", "456"); - - when(session.getAttribute("user")).thenReturn(user); - when(accountRepository.getAccountBalance(123, 456)).thenReturn(500.0); - when(accountRepository.getUserAccountsById(123)).thenReturn((List) mockAccounts); - // Act - ResponseEntity result = transactController.deposit(requestMap, session); - // Assert - assertEquals(HttpStatus.OK, result.getStatusCode()); - Map responseBody = (Map) result.getBody(); + depositRequestMap.put("deposit_amount", "250.0"); + depositRequestMap.put("account_id", "456"); + + when(mockHttpSession.getAttribute("user")).thenReturn(testUser); + when(mockAccountRepository.getAccountBalance(123, 456)).thenReturn(500.0); + when(mockAccountRepository.getUserAccountsById(123)).thenReturn((List) mockUserAccounts); + + ResponseEntity actualResponse = transactController.deposit(depositRequestMap, mockHttpSession); + + assertEquals(HttpStatus.OK, actualResponse.getStatusCode()); + Map responseBody = (Map) actualResponse.getBody(); assertNotNull(responseBody); assertEquals("Amount Deposited Successfully.", responseBody.get("message")); - assertEquals(mockAccounts, responseBody.get("accounts")); + assertEquals(mockUserAccounts, responseBody.get("accounts")); - verify(accountRepository).getAccountBalance(123, 456); - verify(accountRepository).changeAccountsBalanceById(750.0, 456); - verify(transactRepository).logTransaction(eq(456), eq("deposit"), eq(250.0), eq("online"), eq("success"), + verify(mockAccountRepository).getAccountBalance(123, 456); + verify(mockAccountRepository).changeAccountsBalanceById(750.0, 456); + verify(mockTransactRepository).logTransaction(eq(456), eq("deposit"), eq(250.0), eq("online"), eq("success"), eq("Deposit Transaction Successfull"), any(LocalDateTime.class)); - verify(accountRepository).getUserAccountsById(123); + verify(mockAccountRepository).getUserAccountsById(123); } -} \ No newline at end of file +}