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

[BE/TEST] 각종 테스트 #376

Merged
merged 13 commits into from
Jul 19, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,12 @@
@Slf4j
public class LoggingFilter extends OncePerRequestFilter {
private final List<String> excludeUrl =
List.of("/actuator/health", "/actuator/prometheus", "/v1/health");
List.of(
"/actuator/health",
"/actuator/prometheus",
"/v1/health",
"/api-docs/swagger-config",
"/api-docs");

@Override
protected void doFilterInternal(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
import com.gaebaljip.exceed.member.domain.Activity;
import com.gaebaljip.exceed.member.domain.Gender;

import lombok.Builder;

@Builder
public record UpdateMemberRequest(
@NotNull(message = "키를 " + ValidationMessage.NOT_NULL)
@Min(value = 0, message = "키는 " + ValidationMessage.MIN_0)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

Expand All @@ -16,8 +17,8 @@
import com.gaebaljip.exceed.common.event.UpdateWeightEvent;
import com.gaebaljip.exceed.dto.request.UpdateWeightRequest;
import com.gaebaljip.exceed.dto.response.UpdateWeightResponse;
import com.gaebaljip.exceed.member.application.UpdateWeightService;
import com.gaebaljip.exceed.member.application.port.in.UpdateWeightCommand;
import com.gaebaljip.exceed.member.application.port.in.UpdateWeightUsecase;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
Expand All @@ -30,16 +31,16 @@
@SecurityRequirement(name = "access-token")
@Tag(name = "[몸무게 수정]")
public class UpdateWeightController {
private final UpdateWeightService updateWeightService;
private final UpdateWeightUsecase updateWeightUsecase;

@Operation(summary = "회원 몸무게 및 목표 몸무게 수정", description = "회원 몸무게 및 목표 몸무게를 수정한다.")
@PatchMapping("/members/weight")
public ApiResponse<UpdateWeightResponse> updateWeight(
HttpServletRequest servletRequest,
UpdateWeightRequest request,
@RequestBody UpdateWeightRequest request,
@AuthenticationMemberId Long memberId) {
UpdateWeightResponse response =
updateWeightService.execute(
updateWeightUsecase.execute(
UpdateWeightCommand.of(request.weight(), request.targetWeight(), memberId));
Events.raise(
UpdateWeightEvent.from(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.gaebaljip.exceed.infrastructure.adapter.in;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import com.gaebaljip.exceed.common.ControllerTest;
import com.gaebaljip.exceed.common.WithMockUser;
import com.gaebaljip.exceed.infrastructure.sse.adapter.in.EmitterController;
import com.gaebaljip.exceed.infrastructure.sse.application.port.in.ConnectEmitterUseCase;

@WebMvcTest(EmitterController.class)
public class EmitterControllerTest extends ControllerTest {

@MockBean private ConnectEmitterUseCase connectEmitterUseCase;

@Test
@WithMockUser(memberId = 1L)
void when_connect_expected_success() throws Exception {

// given
given(connectEmitterUseCase.execute(any(), any())).willReturn(new SseEmitter());

// when
ResultActions resultActions =
mockMvc.perform(get("/api/emitter/connect").contentType("text/event-stream"));

// then
resultActions.andExpect(status().isOk());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.gaebaljip.exceed.member;

import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.ResultActions;

import com.gaebaljip.exceed.common.IntegrationTest;
import com.gaebaljip.exceed.common.WithMockUser;
import com.gaebaljip.exceed.member.adapter.out.persistence.MemberRepository;

public class DeleteMemberIntegrationTest extends IntegrationTest {
@Autowired private MemberRepository memberRepository;

@Test
@WithMockUser(memberId = 1L)
@DisplayName("회원 탈퇴 성공")
void deleteMember() throws Exception {

// given
long memberId = 1L;
// when
ResultActions resultActions = mockMvc.perform(delete("/v1/members"));

// eye
String responseBody = resultActions.andReturn().getResponse().getContentAsString();

// then
resultActions.andExpect(status().isOk());
assertAll(() -> assertFalse(memberRepository.existsById(memberId)));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

회원 탈퇴시 회원 이외에도 제거되는 데이터들도 검증에 포함되어 있으면 좋을 것 같습니다.

Copy link
Collaborator Author

@LJH098 LJH098 Jul 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

그런데 굳이 이벤트까지 써가면서 결합도를 낮췄는데 테스트에서 결합도를 높일 필요가 있나 싶어요

Controller 테스트에서 이벤트가 잘 publish되는지 테스트도 하고 있어서 굳이 다른 데이터가 삭제 되었는지 확인 할필요 없지않나

Copy link
Collaborator

@hwangdaesun hwangdaesun Jul 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

테스트의 목적이 해당 기능이 의도하는 데로 확인하는 거 아닌가요?
결합도가 올라간다고 통합 테스트시 해야갈 검증을 안 하는 거는 옳지 않다고 생각합니다.

}

@Test
@WithMockUser(memberId = 100000L)
@DisplayName("회원 탈퇴 실패 : 회원이 존재하지 않음")
void deleteMember_fail() throws Exception {

// given

// when
ResultActions resultActions = mockMvc.perform(delete("/v1/members"));

// eye
String responseBody = resultActions.andReturn().getResponse().getContentAsString();

// then
resultActions.andExpectAll(status().isBadRequest(), jsonPath("$.error.code").value("4448"));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.gaebaljip.exceed.member;

import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.ResultActions;

import com.gaebaljip.exceed.common.IntegrationTest;
import com.gaebaljip.exceed.common.WithMockUser;
import com.gaebaljip.exceed.member.adapter.out.persistence.MemberEntity;
import com.gaebaljip.exceed.member.adapter.out.persistence.MemberRepository;

public class GetWeightIntegrationTest extends IntegrationTest {

@Autowired private MemberRepository memberRepository;

@Test
@WithMockUser(memberId = 1L)
@DisplayName("몸무게 조회 성공")
void when_getWeight_expected_success() throws Exception {
// given
long memberId = 1L;

// when
ResultActions resultActions = mockMvc.perform(get("/v1/members/weight"));

MemberEntity member = memberRepository.findById(memberId).get();

// then
resultActions.andExpect(status().isOk());
assertAll(
() -> assertEquals(member.getWeight(), 70.0),
() -> assertEquals(member.getTargetWeight(), 68.0));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package com.gaebaljip.exceed.member;

import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.ResultActions;

import com.gaebaljip.exceed.common.IntegrationTest;
import com.gaebaljip.exceed.common.WithMockUser;
import com.gaebaljip.exceed.dto.request.UpdateMemberRequest;
import com.gaebaljip.exceed.member.adapter.out.persistence.MemberEntity;
import com.gaebaljip.exceed.member.adapter.out.persistence.MemberRepository;
import com.gaebaljip.exceed.member.exception.MemberError;

public class UpdateMemberIntegrationTest extends IntegrationTest {

@Autowired private MemberRepository memberRepository;

@Test
@WithMockUser(memberId = 1L)
@DisplayName("회원 수정 성공")
void when_updateMember_expected_success() throws Exception {
// given
Long memberId = 1L;

UpdateMemberRequest updateMemberRequest =
UpdateMemberRequest.builder()
.height(180.3)
.activity("VERY_ACTIVE")
.age(40)
.gender("MALE")
.etc("회원 수정")
.build();

// when
ResultActions resultActions =
mockMvc.perform(
put("/v1/members")
.content(om.writeValueAsString(updateMemberRequest))
.contentType(MediaType.APPLICATION_JSON));
MemberEntity member = memberRepository.findById(memberId).get();
// then
resultActions.andExpectAll(status().isOk());
assertAll(
() -> assertEquals(member.getHeight(), updateMemberRequest.height()),
() -> assertEquals(member.getActivity().name(), updateMemberRequest.activity()),
() -> assertEquals(member.getAge(), updateMemberRequest.age()),
() -> assertEquals(member.getGender().name(), updateMemberRequest.gender()),
() -> assertEquals(member.getEtc(), updateMemberRequest.etc()));
}

@Test
@WithMockUser(memberId = 1000L)
@DisplayName("회원 수정 실패 - 회원이 존재하지 않음")
void when_updateMember_member_invalid_expected_exception() throws Exception {
// given
UpdateMemberRequest updateMemberRequest =
UpdateMemberRequest.builder()
.height(180.3)
.activity("VERY_ACTIVE")
.age(40)
.gender("MALE")
.etc("회원 수정")
.build();

// when
ResultActions resultActions =
mockMvc.perform(
put("/v1/members")
.content(om.writeValueAsString(updateMemberRequest))
.contentType(MediaType.APPLICATION_JSON));

// then
resultActions.andExpectAll(
status().isBadRequest(),
jsonPath("$.error.reason").value(MemberError.INVALID_MEMBER.getReason()));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.gaebaljip.exceed.member;

import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.ResultActions;

import com.gaebaljip.exceed.common.IntegrationTest;
import com.gaebaljip.exceed.common.WithMockUser;
import com.gaebaljip.exceed.dto.request.UpdateWeightRequest;
import com.gaebaljip.exceed.member.adapter.out.persistence.MemberEntity;
import com.gaebaljip.exceed.member.adapter.out.persistence.MemberRepository;

public class UpdateWeightIntegrationTest extends IntegrationTest {
@Autowired private MemberRepository memberRepository;

@Test
@DisplayName("몸무게 수정 성공")
@WithMockUser(memberId = 1L)
void when_updateWeight_expected_success() throws Exception {
// given
Long memberId = 1L;
UpdateWeightRequest updateWeightRequest =
UpdateWeightRequest.builder().weight(50.0).targetWeight(70.5).build();

// when
ResultActions resultActions =
mockMvc.perform(
patch("/v1/members/weight")
.content(om.writeValueAsString(updateWeightRequest))
.contentType(MediaType.APPLICATION_JSON));
MemberEntity member = memberRepository.findById(memberId).get();

// then
resultActions.andExpectAll(status().isOk());
assertAll(
() -> assertEquals(updateWeightRequest.weight(), member.getWeight()),
() -> assertEquals(updateWeightRequest.targetWeight(), member.getTargetWeight()));
}
}
Loading