Authentication and Verification Flows - Auth Service Test Coverage and Behavioral Guarantees

src/test/java/com/bankasap/service/AuthServiceTest.java

src/main/java/com/bankasap/service/AuthService.java

src/main/java/com/bankasap/controller/AuthController.java

Overview

The visible test suite focuses on the service-layer authentication paths that drive the controller endpoints under @RestController /auth. AuthServiceTest verifies the happy-path behavior for signup, signup verification, signup code resend, login, 2FA verification, and login code resend by isolating AuthService with Mockito mocks for UserRepository, EmailService, and PasswordEncoder.

AuthController is a thin adapter over those service methods: each handler reads a request DTO, calls the matching AuthService method, and wraps the returned message in new AuthResponse(message). The tests therefore guarantee the service messages and key side effects that the controller exposes through ResponseEntity.ok, even though no controller test class is present in the provided source set.

EmailServiceTest adds a separate guarantee for outbound email formatting. It verifies the exact subject and body text for sendTwoFactorCode and sendAccountLockedEmail, which matters because AuthService relies on EmailService.sendTwoFactorCode when generating signup and login verification codes.

Test Fixture and Dependency Wiring

AuthServiceTest

src/test/java/com/bankasap/service/AuthServiceTest.java

AuthServiceTest uses @ExtendWith(MockitoExtension.class) to initialize three mocks and one injected service instance. The visible fixture proves that the suite tests AuthService in isolation rather than through Spring MVC or a real repository.

Property Type Test Role
userRepository UserRepository Mocked persistence dependency used by AuthService
emailService EmailService Mocked mail dependency used to capture code delivery calls
passwordEncoder PasswordEncoder Mocked password encoder used in signup and login setup
authService AuthService Injected service under test

Fixture behavior visible in the test class

  • @Mock creates the repository, email service, and password encoder doubles.
  • @InjectMocks constructs AuthService with those doubles.
  • ArgumentCaptor is used to inspect generated verification codes and persisted User objects.
  • clearInvocations(emailService) is used in the helper path to discard prior email calls before later assertions.

AuthService

src/main/java/com/bankasap/service/AuthService.java

The service maintains one in-memory list for pending signup flows and delegates persistence and email delivery to injected collaborators.

Property Type Role in tested flows
emailService EmailService Sends 2FA and signup verification codes
formatter DateTimeFormatter Formats lock-until timestamps in lock messages
passwordEncoder PasswordEncoder Encodes signup passwords and checks login credentials
pendingSignUps List<PendingSignUp> Holds unverified signup state in memory
userRepository UserRepository Looks up and stores User records

AuthController

src/main/java/com/bankasap/controller/AuthController.java

The controller does not introduce additional branching. It forwards request DTO fields into AuthService and wraps the returned string in AuthResponse.

Property Type Role in runtime delegation
authService AuthService Delegates all auth and verification requests

Verified Behavioral Coverage

signUp

src/main/java/com/bankasap/service/AuthService.java

src/main/java/com/bankasap/controller/AuthController.java

src/test/java/com/bankasap/service/AuthServiceTest.java

Test Controller endpoint Verified behavior Assertions and side effects
signUp_ValidCredentials_ShouldCreatePendingUserAndSendEmail POST /signup A valid signup request returns the signup confirmation message, generates a verification code, and sends it by email without saving a user yet. Asserts "Signup verification code sent to email", captures the code passed to sendTwoFactorCode, checks the code length is 10, and verifies userRepository.save(any(User.class)) is never called.

What the test proves:

  • AuthService.signUp accepts matching passwords when the encoder mock is available.
  • The generated code is sent through EmailService.sendTwoFactorCode.
  • Signup does not persist a User until verification completes.

verifySignUp

src/main/java/com/bankasap/service/AuthService.java

src/main/java/com/bankasap/controller/AuthController.java

src/test/java/com/bankasap/service/AuthServiceTest.java

Test Controller endpoint Verified behavior Assertions and side effects
verifySignUp_CorrectCode_ShouldRegisterUser POST /verify-signup A matching signup code registers the user and returns the success message. Asserts "User registered successfully", captures the saved User, checks savedUser.getEmail() equals the signup email, and checks savedUser.getPassword() equals "encodedPassword123".

What the test proves:

  • AuthService.verifySignUp saves a User using the encoded password produced during signup.
  • The persisted record is created only after code validation succeeds.

resendSignUpCode

src/main/java/com/bankasap/service/AuthService.java

src/main/java/com/bankasap/controller/AuthController.java

src/test/java/com/bankasap/service/AuthServiceTest.java

Test Controller endpoint Verified behavior Assertions and side effects
resendSignUpCode_ValidEmail_ShouldGenerateNewCodeAndEmail POST /resend-signup-code A pending signup can request a new code and the service returns the resend confirmation message. Asserts "New signup verification code sent to email", captures the resent code passed to sendTwoFactorCode, and checks the code length is 10.

What the test proves:

  • The service can regenerate a signup verification code for an existing pending signup.
  • The resend path still uses EmailService.sendTwoFactorCode.

login

src/main/java/com/bankasap/service/AuthService.java

src/main/java/com/bankasap/controller/AuthController.java

src/test/java/com/bankasap/service/AuthServiceTest.java

Test Controller endpoint Verified behavior Assertions and side effects
login_ValidCredentials_ShouldReturnSuccess POST /login A valid login request returns the 2FA delivery message and sends a code by email. Asserts "2FA code sent to email", captures the code sent through sendTwoFactorCode, and checks the code length is 10.

What the test proves:

  • AuthService.login reaches the 2FA generation branch when PasswordEncoder.matches is stubbed to succeed.
  • The login path emits a verification code rather than returning success immediately.

verifyCode

src/main/java/com/bankasap/service/AuthService.java

src/main/java/com/bankasap/controller/AuthController.java

src/test/java/com/bankasap/service/AuthServiceTest.java

Test Controller endpoint Verified behavior Assertions and side effects
verifyCode_Correct2FACode_ShouldAuthenticate POST /verify-code A correct login 2FA code returns the login success message. Asserts "Login successful".

What the test proves:

  • AuthService.verifyCode accepts the generated 2FA code produced during login.
  • The visible suite treats successful 2FA verification as the final authentication success condition.

resendCode

src/main/java/com/bankasap/service/AuthService.java

src/main/java/com/bankasap/controller/AuthController.java

src/test/java/com/bankasap/service/AuthServiceTest.java

Test Controller endpoint Verified behavior Assertions and side effects
resendCode_ValidEmail_ShouldSendNew2FACode POST /resend-login-code A logged-in user can request a fresh 2FA code and the service returns the resend confirmation message. Asserts "New 2FA code sent to email", captures the code sent through sendTwoFactorCode, and checks the code length is 10.

What the test proves:

  • AuthService.resendCode generates a new 2FA code for the user path exercised by the test.
  • The resend path again depends on EmailService.sendTwoFactorCode.

Test Harness Helper

registerUser

src/test/java/com/bankasap/service/AuthServiceTest.java

registerUser is the private test helper that sets up the login and resend-code scenarios. It signs up a user, captures the signup code, verifies the signup, and then clears email-service invocations.

Helper Purpose
registerUser Establishes a verified user state for later login-related tests

This helper is what allows the later tests to focus on authentication behavior instead of repeating the signup setup.

Email Service Test Coverage

EmailService

[!NOTE] AuthService.findUserByEmail reads only from userRepository.findAll(), while the visible registerUser helper does not stub findAll() to return the registered user. The login and resend-code success tests therefore rely on repository behavior that the shown mock setup does not define.

src/main/java/com/bankasap/service/EmailService.java

EmailService is the outbound mail wrapper used by AuthService for verification-code delivery and account-lock notification composition.

Property Type Role in tested flows
mailSender JavaMailSender Sends the constructed SimpleMailMessage
Method Description
sendTwoFactorCode Builds a SimpleMailMessage with the 2FA subject and code text, then sends it through mailSender.
sendAccountLockedEmail Builds a SimpleMailMessage with the account-locked subject and fixed lock message, then sends it through mailSender.

EmailServiceTest

src/test/java/com/bankasap/service/EmailServiceTest.java

Test Verified behavior Assertions and side effects
sendTwoFactorCode_ShouldSendEmailWithCode Verifies the recipient, subject, and body text for a 2FA code email. Checks message.getTo(), message.getSubject(), and message.getText().
sendAccountLockedEmail_ShouldSendLockNotification Verifies the recipient, subject, and body text for a lock notification email. Checks message.getTo(), message.getSubject(), and message.getText().

This test class proves the literal email strings used by EmailService, which gives the auth flow a fixed message contract for outbound mail.

Controller Linkage Under Test

AuthController

src/main/java/com/bankasap/controller/AuthController.java

Controller method Endpoint Delegated service method Response wrapper
signUp POST /signup signUp new AuthResponse(message)
verifySignUp POST /verify-signup verifySignUp new AuthResponse(message)
resendSignUpCode POST /resend-signup-code resendSignUpCode new AuthResponse(message)
login POST /login login new AuthResponse(message)
verifyCode POST /verify-code verifyCode new AuthResponse(message)
resendCode POST /resend-login-code resendCode new AuthResponse(message)

The tests do not exercise AuthController directly, but they validate the return strings and side effects that the controller wraps into AuthResponse.

Coverage Gaps Visible in the Suite

[!NOTE] AuthService.login sets lockedUntil with LocalDateTime.now().plusSeconds(15) while returning the message Account locked for 15 minutes. The visible test suite does not cover this branch, so the stored lock duration and the user-facing message diverge in the current source.

The provided AuthServiceTest covers only the success paths listed above. The following branches in AuthService are not exercised by the visible tests:

  • signUp
    • existing user rejection
    • invalid email format rejection
    • invalid password rejection
    • password mismatch rejection
    • replacement of an existing pending signup entry for the same email
  • verifySignUp
    • no pending signup started
    • expired signup code
    • invalid signup code
  • resendSignUpCode
    • no pending signup started
  • login
    • user not found
    • locked account branch
    • failed password attempts one and two
    • lockout branch after repeated failures
    • reset of failedLoginAttempts and lockedUntil after success
  • verifyCode
    • user not found
    • no 2FA code generated
    • expired 2FA code
    • invalid 2FA code
    • clearing of twoFactorCode and twoFactorCodeExpiresAt
  • resendCode
    • user not found
    • locked account branch
    • clearing or replacement of any prior 2FA state is not asserted
  • EmailService
    • no AuthService path calls sendAccountLockedEmail
    • sendAccountLockedEmail is only covered by EmailServiceTest

Behavioral Guarantees Summary

[!NOTE] AuthService.login reaches the lockout branch without calling EmailService.sendAccountLockedEmail. The lock-notification method is verified only by EmailServiceTest, not by any visible auth-flow test.

  • signUp returns the signup verification message, generates a 10-character code, and sends it through EmailService.
  • verifySignUp persists a User only after a correct code is supplied.
  • resendSignUpCode and resendCode both regenerate 10-character codes and send them through EmailService.
  • login returns the 2FA delivery message and sends a code when password matching succeeds.
  • verifyCode returns Login successful when the captured code is replayed successfully.
  • EmailServiceTest verifies the exact subject and body text for both 2FA and lock emails.