Skip to content

Commit

Permalink
test: API 변경에 따른 통합 테스트 수정 및 단위 테스트 구현 (#104)
Browse files Browse the repository at this point in the history
  • Loading branch information
choidongkuen committed Jan 16, 2024
1 parent 0933b86 commit 041df10
Show file tree
Hide file tree
Showing 3 changed files with 213 additions and 7 deletions.
35 changes: 28 additions & 7 deletions src/test/java/net/teumteum/integration/UserIntegrationTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,19 @@

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

import java.util.List;
import net.teumteum.core.error.ErrorResponse;
import net.teumteum.user.domain.User;
import net.teumteum.user.domain.response.FriendsResponse;
import net.teumteum.user.domain.response.UserGetResponse;
import net.teumteum.user.domain.response.UserMeGetResponse;
import net.teumteum.user.domain.response.*;
import net.teumteum.user.domain.response.UserRegisterResponse;
import net.teumteum.user.domain.response.UsersGetByIdResponse;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

import java.util.List;

@DisplayName("유저 통합테스트의")
class UserIntegrationTest extends IntegrationTest {

Expand Down Expand Up @@ -125,10 +127,10 @@ void Return_my_info_if_valid_token_received() {

// then
Assertions.assertThat(result.expectStatus().isOk()
.expectBody(UserMeGetResponse.class)
.returnResult()
.getResponseBody())
.usingRecursiveComparison().isEqualTo(expected);
.expectBody(UserMeGetResponse.class)
.returnResult()
.getResponseBody())
.usingRecursiveComparison().isEqualTo(expected);
}

}
Expand Down Expand Up @@ -301,6 +303,25 @@ void Return_400_badRequest_register_user_card() {
Assertions.assertThat(responseBody)
.isNotNull();
}

@Test
@DisplayName("요청 값의 유효성 검사가 실패하면, 400 에러를 반환한다.")
void Return_400_badRequest_if_not_meet_request_condition() {
// given
var existUser = repository.saveAndGetUser();

var userRegister = RequestFixture.userRegisterRequestWithNoValid(existUser);
// when
var result = api.registerUserCard(VALID_TOKEN, userRegister);

// then
ErrorResponse responseBody = result.expectStatus().isBadRequest()
.expectBody(ErrorResponse.class)
.returnResult().getResponseBody();

Assertions.assertThat(responseBody)
.isNotNull();
}
}

@Nested
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package net.teumteum.unit.user.controller;

import static net.teumteum.unit.auth.common.SecurityValue.VALID_ACCESS_TOKEN;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.springframework.http.HttpHeaders.AUTHORIZATION;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import net.teumteum.core.security.SecurityConfig;
import net.teumteum.core.security.filter.JwtAuthenticationFilter;
import net.teumteum.core.security.service.JwtService;
import net.teumteum.core.security.service.RedisService;
import net.teumteum.core.security.service.SecurityService;
import net.teumteum.integration.RequestFixture;
import net.teumteum.user.controller.UserController;
import net.teumteum.user.domain.User;
import net.teumteum.user.domain.UserFixture;
import net.teumteum.user.domain.request.UserRegisterRequest;
import net.teumteum.user.domain.response.UserRegisterResponse;
import net.teumteum.user.service.UserService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper;

@WebMvcTest(value = UserController.class,
excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = SecurityConfig.class),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = JwtAuthenticationFilter.class),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = RedisService.class),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = JwtService.class)}
)
@WithMockUser
@DisplayName("유저 컨트롤러 단위 테스트의")
public class UserControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private UserService userService;

@MockBean
private SecurityService securityService;

private User user;

@BeforeEach
void setUp() {
user = UserFixture.getIdUser();
}

@Nested
@DisplayName("유저 카드 등록 API는")
class Register_user_card_api_unit {

@Test
@DisplayName("유효한 사용자의 등록 요청값이 주어지면, 201 Created 상태값을 반환한다.")
void Register_user_card_with_201_created() throws Exception {
// given
UserRegisterRequest request = RequestFixture.userRegisterRequest(user);

UserRegisterResponse response = new UserRegisterResponse(1L);

given(userService.register(any(UserRegisterRequest.class))).willReturn(response);

// when & then
mockMvc.perform(post("/users")
.content(new ObjectMapper().writeValueAsString(request))
.contentType(APPLICATION_JSON)
.with(csrf())
.header(AUTHORIZATION, VALID_ACCESS_TOKEN))
.andDo(print())
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id").value(1));
}

@Test
@DisplayName("유효하지 않은 사용자의 등록 요청값이 주어지면, 400 Bad Request 상태값을 반환한다.")
void Register_user_card_with_400_bad_request() throws Exception {
// given
UserRegisterRequest request = RequestFixture.userRegisterRequestWithNoValid(user);
// when
// then
mockMvc.perform(post("/users")
.content(new ObjectMapper().writeValueAsString(request))
.contentType(APPLICATION_JSON)
.with(csrf())
.header(AUTHORIZATION, VALID_ACCESS_TOKEN))
.andDo(print())
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.message").value("이름은 필수 입력값입니다."));
}
}
}
78 changes: 78 additions & 0 deletions src/test/java/net/teumteum/unit/user/service/UserServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package net.teumteum.unit.user.service;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;

import net.teumteum.core.security.service.RedisService;
import net.teumteum.integration.RequestFixture;
import net.teumteum.user.domain.User;
import net.teumteum.user.domain.UserFixture;
import net.teumteum.user.domain.UserRepository;
import net.teumteum.user.domain.request.UserRegisterRequest;
import net.teumteum.user.domain.response.UserRegisterResponse;
import net.teumteum.user.service.UserService;
import org.junit.jupiter.api.BeforeEach;
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;

@ExtendWith(MockitoExtension.class)
@DisplayName("유저 서비스 단위 테스트의")
public class UserServiceTest {

@InjectMocks
UserService userService;

@Mock
UserRepository userRepository;

@Mock
RedisService redisService;

private User user;

@BeforeEach
void setUp() {
user = UserFixture.getIdUser();
}

@Nested
@DisplayName("유저 카드 등록 API는")
class Register_user_card_api_unit {

@Test
@DisplayName("유효한 유저의 요청 값이 들어오는 경우, 정상적으로 유저 카드를 등록한다.")
void If_valid_user_request_register_user_card() {
// given
UserRegisterRequest request = RequestFixture.userRegisterRequest(user);

given(userRepository.save(any(User.class))).willReturn(user);

// when
UserRegisterResponse response = userService.register(request);

// then
assertThat(response.id()).isEqualTo(1);
}

@Test
@DisplayName("사용자가 이미 존재하면, 카드 등록을 실패한다.")
void If_user_already_exist_register_user_card_fail() {
// given
UserRegisterRequest request = RequestFixture.userRegisterRequestWithFail(user);

given(userRepository.findByAuthenticatedAndOAuthId(any(), any()))
.willThrow(new IllegalArgumentException("일치하는 user 가 이미 존재합니다."));

assertThatThrownBy(() -> userService.register(request))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("일치하는 user 가 이미 존재합니다.");
}
}
}

0 comments on commit 041df10

Please sign in to comment.