Skip to content

Commit

Permalink
refactor: User 테스트 리팩토링
Browse files Browse the repository at this point in the history
  • Loading branch information
EunChanNam committed Nov 14, 2023
1 parent 7a44381 commit 1af0781
Show file tree
Hide file tree
Showing 13 changed files with 1,082 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
Expand Down Expand Up @@ -53,4 +55,9 @@ public void addInterceptors(final InterceptorRegistry registry) {
public void addArgumentResolvers(final List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new AuthInfoArgumentResolver(authTokenManager));
}

@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,12 @@ public class FlaskConnector implements AiConnector {
private final String requestUri;
private final RestTemplate restTemplate;

public FlaskConnector(@Value("${flask.domain}") String domain) {
public FlaskConnector(
@Value("${flask.domain}") String domain,
RestTemplate restTemplate
) {
this.requestUri = domain + URL;
this.restTemplate = new RestTemplate();
this.restTemplate = restTemplate;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
package com.inq.wishhair.wesharewishhair.common.support;

import static org.mockito.BDDMockito.*;

import org.junit.jupiter.api.BeforeEach;
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.boot.test.mock.mockito.MockBean;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.core.JsonProcessingException;
Expand All @@ -24,6 +29,15 @@ public abstract class ApiTestSupport {
@Autowired
private UserRepository userRepository;

@MockBean
private PasswordEncoder passwordEncoder;

@BeforeEach
void setPasswordEncoder() {
given(passwordEncoder.encode(any())).willReturn("password");
given(passwordEncoder.matches(any(), any())).willReturn(true);
}

protected String getAccessToken(Long userId) {
return authTokenManager.generate(userId).accessToken();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ void fail() {
}

@Test
@DisplayName("[]")
@DisplayName("[특정 작성자의 리뷰를 조회한다]")
void findWithPhotosByUserId() {
//given
List<Review> reviews = List.of(ReviewFixture.getReview());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package com.inq.wishhair.wesharewishhair.user.application;

import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.ThrowableAssert.*;
import static org.mockito.BDDMockito.*;

import java.util.Optional;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;

import com.inq.wishhair.wesharewishhair.common.support.MockTestSupport;
import com.inq.wishhair.wesharewishhair.global.exception.ErrorCode;
import com.inq.wishhair.wesharewishhair.global.exception.WishHairException;
import com.inq.wishhair.wesharewishhair.user.domain.UserRepository;
import com.inq.wishhair.wesharewishhair.user.domain.entity.Email;
import com.inq.wishhair.wesharewishhair.user.domain.entity.User;
import com.inq.wishhair.wesharewishhair.user.fixture.UserFixture;

@DisplayName("[UserFindService 테스트] - Application")
class UserFindServiceTest extends MockTestSupport {

@InjectMocks
private UserFindService userFindService;
@Mock
private UserRepository userRepository;

@Nested
@DisplayName("[id 로 유저를 조회한다]")
class getById {

private final Long userId = 1L;

@Test
@DisplayName("[조회에 성공한다]")
void success() {
//given
User user = UserFixture.getFixedManUser();
given(userRepository.findById(userId))
.willReturn(Optional.of(user));

//when
User actual = userFindService.findByUserId(userId);

//then
assertThat(actual).isEqualTo(user);
}

@Test
@DisplayName("[id 에 맞는 유저가 존재하지 않아 실패한다]")
void fail() {
//given
given(userRepository.findById(userId))
.willReturn(Optional.empty());

//when
ThrowingCallable when = () -> userFindService.findByUserId(userId);

//then
assertThatThrownBy(when)
.isInstanceOf(WishHairException.class)
.hasMessageContaining(ErrorCode.NOT_EXIST_KEY.getMessage());
}
}

@Nested
@DisplayName("[email 로 유저를 조회한다]")
class getByEmail {

private final Email email = new Email("[email protected]");

@Test
@DisplayName("[조회에 성공한다]")
void success() {
//given
User user = UserFixture.getFixedManUser();
given(userRepository.findByEmail(email))
.willReturn(Optional.of(user));

//when
User actual = userFindService.findByEmail(email);

//then
assertThat(actual).isEqualTo(user);
}

@Test
@DisplayName("[email 에 맞는 유저가 존재하지 않아 실패한다]")
void fail() {
//given
given(userRepository.findByEmail(email))
.willReturn(Optional.empty());

//when
ThrowingCallable when = () -> userFindService.findByEmail(email);

//then
assertThatThrownBy(when)
.isInstanceOf(WishHairException.class)
.hasMessageContaining(ErrorCode.USER_NOT_FOUND_BY_EMAIL.getMessage());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package com.inq.wishhair.wesharewishhair.user.application;

import static org.assertj.core.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.BDDMockito.*;

import java.util.ArrayList;
import java.util.Optional;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
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.domain.Pageable;

import com.inq.wishhair.wesharewishhair.global.dto.response.PagedResponse;
import com.inq.wishhair.wesharewishhair.hairstyle.domain.hashtag.Tag;
import com.inq.wishhair.wesharewishhair.point.domain.PointLog;
import com.inq.wishhair.wesharewishhair.point.domain.PointLogRepository;
import com.inq.wishhair.wesharewishhair.point.domain.PointType;
import com.inq.wishhair.wesharewishhair.review.application.ReviewSearchService;
import com.inq.wishhair.wesharewishhair.user.application.dto.response.MyPageResponse;
import com.inq.wishhair.wesharewishhair.user.application.dto.response.UserInfo;
import com.inq.wishhair.wesharewishhair.user.application.dto.response.UserInformation;
import com.inq.wishhair.wesharewishhair.user.domain.entity.FaceShape;
import com.inq.wishhair.wesharewishhair.user.domain.entity.User;
import com.inq.wishhair.wesharewishhair.user.fixture.UserFixture;

@ExtendWith(MockitoExtension.class)
@DisplayName("[UserInfoService 테스트] - Application")
class UserInfoServiceTest {

@InjectMocks
private UserInfoService userInfoService;
@Mock
private UserFindService userFindService;
@Mock
private ReviewSearchService reviewSearchService;
@Mock
private PointLogRepository pointLogRepository;

@Nested
@DisplayName("[마이페이지 정보를 조회한다]")
class getMyPageInfo {

@Test
@DisplayName("[포인트 기록이 존재해 잔여 포인트까지 조회한다]")
void hasPointLog() {
//given
User user = UserFixture.getFixedManUser();
given(userFindService.findByUserId(1L)).willReturn(user);

PointLog pointLog = PointLog.addPointLog(user, PointType.CHARGE, 1000, 500);
given(pointLogRepository.findByUserOrderByCreatedDateDesc(user))
.willReturn(Optional.of(pointLog));

given(reviewSearchService.findLikingReviews(eq(1L), any(Pageable.class)))
.willReturn(new PagedResponse<>(new ArrayList<>(), null));

//when
MyPageResponse actual = userInfoService.getMyPageInfo(1L);

//then
assertAll(
() -> assertThat(actual.nickname()).isEqualTo(user.getNicknameValue()),
() -> assertThat(actual.point()).isEqualTo(pointLog.getPoint()),
() -> assertThat(actual.reviews()).isEmpty(),
() -> assertThat(actual.sex()).isEqualTo(user.getSex())
);
}

@Test
@DisplayName("[포인트 기록이 존재하지 않아 0 포인트를 조회한다]")
void noPoint() {
//given
User user = UserFixture.getFixedManUser();
given(userFindService.findByUserId(1L)).willReturn(user);

given(pointLogRepository.findByUserOrderByCreatedDateDesc(user))
.willReturn(Optional.empty());

given(reviewSearchService.findLikingReviews(eq(1L), any(Pageable.class)))
.willReturn(new PagedResponse<>(new ArrayList<>(), null));

//when
MyPageResponse actual = userInfoService.getMyPageInfo(1L);

//then
assertAll(
() -> assertThat(actual.nickname()).isEqualTo(user.getNicknameValue()),
() -> assertThat(actual.point()).isZero(),
() -> assertThat(actual.reviews()).isEmpty(),
() -> assertThat(actual.sex()).isEqualTo(user.getSex())
);
}
}

@Test
@DisplayName("[얼굴형 정보가 포함된 유저의 간단한 정보를 조회한다]")
void getUserInfo() {
//given
User user = UserFixture.getFixedManUser();
user.updateFaceShape(new FaceShape(Tag.ROUND));
given(userFindService.findByUserId(1L)).willReturn(user);

//when
UserInfo actual = userInfoService.getUserInfo(1L);

//then
assertAll(
() -> assertThat(actual.hasFaceShape()).isTrue(),
() -> assertThat(actual.faceShapeTag()).isEqualTo(Tag.ROUND.getDescription())
);
}

@Test
@DisplayName("[유저 상세정보를 조회한다]")
void getUserInformation() {
//given
User user = UserFixture.getFixedManUser();
given(userFindService.findByUserId(1L)).willReturn(user);

//when
UserInformation actual = userInfoService.getUserInformation(1L);

//then
assertAll(
() -> assertThat(actual.email()).isEqualTo(user.getEmailValue()),
() -> assertThat(actual.name()).isEqualTo(user.getName()),
() -> assertThat(actual.nickname()).isEqualTo(user.getNicknameValue()),
() -> assertThat(actual.sex()).isEqualTo(user.getSex())
);
}
}
Loading

0 comments on commit 1af0781

Please sign in to comment.