Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: 로그인 test 코드 작성 /#34 #40

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
@RequestMapping("${api.prefix}/clubs")
public class ClubController {

private final ClubService clubService;
private static final Long USER_ID = 1L;
private final ClubService clubService;

@GetMapping("/{clubId}")
public ResponseEntity<APISuccessResponse<ClubDetailResponse>> getClub(@Authentication AuthCredential authCredential, @PathVariable("clubId") final Long clubId) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package com.greedy.mokkoji.api.club.dto.club;

import com.greedy.mokkoji.enums.recruitment.RecruitStatus;
import com.greedy.mokkoji.enums.club.ClubAffiliation;
import com.greedy.mokkoji.enums.club.ClubCategory;
import com.greedy.mokkoji.enums.recruitment.RecruitStatus;
import lombok.Builder;

@Builder
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import com.greedy.mokkoji.api.auth.controller.argumentResolver.AuthCredential;
import com.greedy.mokkoji.api.auth.controller.argumentResolver.Authentication;
import com.greedy.mokkoji.api.jwt.JwtUtil;
import com.greedy.mokkoji.api.user.dto.request.LoginRequest;
import com.greedy.mokkoji.api.user.dto.request.UpdateUserInformationRequest;
import com.greedy.mokkoji.api.user.dto.resopnse.LoginResponse;
Expand All @@ -26,7 +25,6 @@ public class UserController {

private final UserService userService;
private final TokenService tokenService;
private final JwtUtil jwtUtil;

@PostMapping("/auth/login")
public ResponseEntity<APISuccessResponse<LoginResponse>> login(@RequestBody LoginRequest request) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package com.greedy.mokkoji.db.club.repository;

import com.greedy.mokkoji.db.club.entity.Club;
import com.greedy.mokkoji.enums.recruitment.RecruitStatus;
import com.greedy.mokkoji.enums.club.ClubAffiliation;
import com.greedy.mokkoji.enums.club.ClubCategory;
import com.greedy.mokkoji.enums.recruitment.RecruitStatus;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package com.greedy.mokkoji.db.club.repository;

import com.greedy.mokkoji.db.club.entity.Club;
import com.greedy.mokkoji.enums.recruitment.RecruitStatus;
import com.greedy.mokkoji.enums.club.ClubAffiliation;
import com.greedy.mokkoji.enums.club.ClubCategory;
import com.greedy.mokkoji.enums.recruitment.RecruitStatus;
import com.querydsl.core.types.dsl.*;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.RequiredArgsConstructor;
Expand All @@ -17,8 +17,8 @@
import java.util.List;
import java.util.Optional;

import static com.greedy.mokkoji.db.club.entity.QClub.*;
import static com.greedy.mokkoji.db.recruitment.entity.QRecruitment.*;
import static com.greedy.mokkoji.db.club.entity.QClub.club;
import static com.greedy.mokkoji.db.recruitment.entity.QRecruitment.recruitment;
import static com.greedy.mokkoji.enums.recruitment.RecruitStatus.OPEN;

@Repository
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.greedy.mokkoji.external;

import com.greedy.mokkoji.api.external.SejongLoginClient;
import com.greedy.mokkoji.api.user.dto.resopnse.StudentInformationResponse;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest
class SejongLoginClientTest {

@Autowired
private SejongLoginClient sejongLoginClient;

@Value("${id}")
private String studentId;

@Value("${password}")
private String password;


@Test
void 외부URL에서_회원정보_가져오기() {
//when
StudentInformationResponse response = sejongLoginClient.getStudentInformation(studentId, password);

// then
assertThat(response).isNotNull();
assertThat(response.name()).isNotEmpty();
assertThat(response.department()).isNotEmpty();
assertThat(response.grade()).isNotEmpty();

System.out.println("회원정보 가져오기 성공: " + response);
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.greedy.mokkoji.notification;

import com.greedy.mokkoji.api.notification.service.EmailNotificationChannel;
import jakarta.mail.MessagingException;
import jakarta.mail.Session;
import jakarta.mail.internet.MimeMessage;
import org.junit.jupiter.api.*;
Expand All @@ -16,7 +15,8 @@
import java.time.LocalDateTime;
import java.util.List;

import static org.mockito.Mockito.*;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.times;

@ExtendWith(MockitoExtension.class)
@DisplayName("이메일 알림 채널 테스트")
Expand Down
63 changes: 63 additions & 0 deletions src/test/java/com/greedy/mokkoji/user/TokenServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.greedy.mokkoji.user;

import com.greedy.mokkoji.api.jwt.JwtUtil;
import com.greedy.mokkoji.api.user.dto.resopnse.LoginResponse;
import com.greedy.mokkoji.api.user.service.TokenService;
import com.greedy.mokkoji.db.user.entity.User;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.DisplayNameGeneration;
import org.junit.jupiter.api.DisplayNameGenerator;
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.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
@DisplayName("토큰 서비스 테스트")
@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
public class TokenServiceTest {

@InjectMocks
TokenService tokenService;

@Mock
JwtUtil jwtUtil;

@Mock
StringRedisTemplate redisTemplate;

@Mock
ValueOperations<String, String> valueOperations;

@Test
void Login시_토큰을_발급_받을_수_있다() {
// given
final User expected = User.builder()
.name("세종")
.grade("4")
.studentId("학번")
.department("컴공과")
.build();

when(jwtUtil.generateAccessToken(expected.getId())).thenReturn("mockAccessToken");
when(jwtUtil.generateRefreshToken(expected.getId())).thenReturn("mockRefreshToken");

// RedisTemplate Mocking
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
doNothing().when(valueOperations).set(anyString(), anyString(), anyLong(), any());

// when
LoginResponse loginResponse = tokenService.generateToken(expected.getId());

// then
assertThat(loginResponse).isNotNull();
assertThat(loginResponse.accessToken()).isNotBlank();
assertThat(loginResponse.refreshToken()).isNotBlank();
}
}
75 changes: 48 additions & 27 deletions src/test/java/com/greedy/mokkoji/user/UserServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,56 +35,77 @@ public class UserServiceTest {
SejongLoginClient sejongLoginClient;

@Test
void 기존_유저는_로그인을_할_수_있다() {
void 로그인을_할_수_있다() {
//given
final String studentId = "학번";
final String password = "비밀번호";

final StudentInformationResponse studentInformationResponse = StudentInformationResponse.of("혜빈", "컴공과", "4");

final User expected = User.builder()
.name("혜빈")
final User expectedUser = User.builder()
.name("세종")
.grade("4")
.studentId("학번")
.department("컴공과")
.build();

BDDMockito.given(sejongLoginClient.getStudentInformation(any(), any())).willReturn(studentInformationResponse);
BDDMockito.given(userRepository.findByStudentId(any())).willReturn(Optional.ofNullable(expected));
BDDMockito.given(userRepository.findByStudentId(any())).willReturn(Optional.ofNullable(expectedUser));

//when
final User actual = userService.login(studentId, password);
final User actualUser = userService.login(studentId, password);

//then
Assertions.assertThat(actual).usingRecursiveComparison().isEqualTo(expected);
Assertions.assertThat(actualUser).usingRecursiveComparison().isEqualTo(expectedUser);
}

@Test
void 토큰을_발급_받을_수_있다() {
//given
final String studentId = "학번";
final String password = "비밀번호";
void 처음_로그인_시_새로운_User로_등록된다() {
// given
String studentId = "학번";
String password = "비밀번호";

StudentInformationResponse studentInfo = StudentInformationResponse.of("세종", "컴공과", "4");
User expectedUser = User.builder()
.name("세종")
.grade("4")
.studentId(studentId)
.department("컴공과")
.build();

BDDMockito.given(sejongLoginClient.getStudentInformation(any(), any())).willReturn(studentInfo);
BDDMockito.given(userRepository.findByStudentId(any())).willReturn(Optional.empty());
BDDMockito.given(userRepository.save(any())).willAnswer(invocation -> invocation.getArgument(0));

final StudentInformationResponse studentInformationResponse = StudentInformationResponse.of("혜빈", "컴공과", "4");
// when
User newUser = userService.login(studentId, password);

final User expected = User.builder()
.name("혜빈")
// then
Assertions.assertThat(newUser).usingRecursiveComparison().isEqualTo(expectedUser);
}

@Test
void 이미_등록된_사용자가_로그인하면_기존_User_객체가_반환된다() {
// given
String studentId = "학번";
String password = "비밀번호";

User existingUser = User.builder()
.name("세종")
.grade("4")
.studentId("학번")
.studentId(studentId)
.department("컴공과")
.build();

BDDMockito.given(sejongLoginClient.getStudentInformation(any(), any())).willReturn(studentInformationResponse);
BDDMockito.given(userRepository.findByStudentId(any())).willReturn(Optional.ofNullable(expected));
BDDMockito.given(userRepository.findByStudentId(any())).willReturn(Optional.of(existingUser));

//when
final User actual = userService.login(studentId, password);
// when
User returnedUser = userService.login(studentId, password);

//then
Assertions.assertThat(actual).usingRecursiveComparison().isEqualTo(expected);
// then
Assertions.assertThat(returnedUser).usingRecursiveComparison().isEqualTo(existingUser);
BDDMockito.verify(userRepository, BDDMockito.never()).save(any());
}
//유저가 생성되는 지
//유저가 중복생성 안 되는 지
//토큰 재발급 가능한 지
//로그아웃 가능한지

//Todo : access토큰 재발급 테스트
//Todo : 로그아웃 테스트
//Todo : 유저정보 들고오기 테스트
//Todo : 유저정보 업데이트 테스트
}