1+ package kattsyn .dev .rentplace .services ;
2+
3+ import kattsyn .dev .rentplace .enums .AuthType ;
4+ import kattsyn .dev .rentplace .services .impl .VerificationCodeServiceImpl ;
5+ import org .junit .jupiter .api .Test ;
6+ import org .junit .jupiter .api .extension .ExtendWith ;
7+ import org .mockito .InjectMocks ;
8+ import org .mockito .Mock ;
9+ import org .mockito .junit .jupiter .MockitoExtension ;
10+ import kattsyn .dev .rentplace .dtos .CodeResponse ;
11+ import kattsyn .dev .rentplace .entities .VerificationCode ;
12+ import kattsyn .dev .rentplace .exceptions .NotFoundException ;
13+ import kattsyn .dev .rentplace .repositories .VerificationCodeRepository ;
14+
15+ import java .time .LocalDateTime ;
16+ import java .util .Optional ;
17+ import static org .junit .jupiter .api .Assertions .*;
18+ import static org .mockito .ArgumentMatchers .any ;
19+ import static org .mockito .Mockito .*;
20+
21+ @ ExtendWith (MockitoExtension .class )
22+ class VerificationCodeServiceImplTest {
23+
24+ @ Mock
25+ private VerificationCodeRepository verificationCodeRepository ;
26+
27+ @ Mock
28+ private EmailService emailService ;
29+
30+ @ Mock
31+ private UserService userService ;
32+
33+ @ InjectMocks
34+ private VerificationCodeServiceImpl verificationCodeService ;
35+
36+ @ Test
37+ void validateCode_CodeExistsAndMatches_ReturnsTrue () {
38+ String email = "test@example.com" ;
39+ String code = "12345" ;
40+ VerificationCode verificationCode = new VerificationCode (email , code , LocalDateTime .now ().plusMinutes (5 ), LocalDateTime .now ());
41+
42+ when (verificationCodeRepository .findById (email )).thenReturn (Optional .of (verificationCode ));
43+
44+ assertTrue (verificationCodeService .validateCode (email , code ));
45+ }
46+
47+ @ Test
48+ void validateCode_CodeNotFound_ThrowsNotFoundException () {
49+ String email = "notfound@example.com" ;
50+ when (verificationCodeRepository .findById (email )).thenReturn (Optional .empty ());
51+
52+ assertThrows (NotFoundException .class , () -> verificationCodeService .validateCode (email , "12345" ));
53+ }
54+
55+ @ Test
56+ void generateAndSendCode_NewCodeGeneratedAndSaved () {
57+ String email = "new@example.com" ;
58+ when (userService .existsByEmail (email )).thenReturn (false );
59+ when (verificationCodeRepository .findById (email )).thenReturn (Optional .empty ());
60+
61+ CodeResponse response = verificationCodeService .generateAndSendCode (email );
62+
63+ verify (verificationCodeRepository ).save (any (VerificationCode .class ));
64+ verify (emailService ).sendVerificationCode (eq (email ), anyString ());
65+ assertEquals (AuthType .AUTH_REGISTER , response .getAuthType ());
66+ }
67+
68+ @ Test
69+ void generateCode_Returns5DigitCode () {
70+ String code = verificationCodeService .generateCode ();
71+
72+ assertTrue (code .matches ("\\ d{5}" ));
73+ }
74+ }
0 commit comments