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

컨트롤러 테스트 코드 작성 #13

Open
wants to merge 4 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,4 @@ out/
### VS Code ###
.vscode/
src/main/resources/application.properties
/src/main/resources/
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ dependencies {
implementation 'com.h2database:h2'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'junit:junit:4.13.1'
implementation 'junit:junit:4.13.1'
Copy link
Contributor

Choose a reason for hiding this comment

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

junit 4로 쓰셨네요. 저는 5로 작업했는데, 논의 후에 통일해봐도 좋을 것 같아요

runtimeOnly 'mysql:mysql-connector-java'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
Expand All @@ -36,6 +38,7 @@ dependencies {
implementation group: 'com.auth0', name: 'auth0', version: "$auth0_auth0_version"
implementation group: 'com.auth0', name: 'java-jwt', version: "$auth0_java_jwt_version"
implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.4'
implementation 'com.google.code.gson:gson:2.9.0'
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public MemberRestController(MemberService memberService, Jwt jwt) {
public ApiRes<RegisterResult> register(
@ModelAttribute RegisterRequest request,
@RequestPart(required = false)MultipartFile imageFile
){
){

Member member = memberService.register(Member.builder()
.email(new Email(request.getEmail()))
Expand All @@ -43,4 +43,4 @@ public ApiRes<RegisterResult> register(
return ApiRes.SUCCESS(new RegisterResult(new MemberDto(member), token));
}

}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package com.gdsc.pknu.backend.controller.user;

import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

@Getter
@Setter
@Builder
public class RegisterRequest {
private String email;
private String password;
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/com/gdsc/pknu/backend/domain/member/Role.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
package com.gdsc.pknu.backend.domain.member;

import com.google.gson.annotations.SerializedName;

import java.io.Serial;
import java.util.Arrays;

public enum Role {
@SerializedName("ROLE_USER")
USER("ROLE_USER"),
@SerializedName("ROLE_ADMIN")
ADMIN("ROLE_ADMIN");

private final String value;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package com.gdsc.pknu.backend.controller.user;

import com.gdsc.pknu.backend.controller.ApiRes;
import com.gdsc.pknu.backend.domain.authentication.Jwt;
import com.gdsc.pknu.backend.domain.member.Email;
import com.gdsc.pknu.backend.domain.member.Member;
import com.gdsc.pknu.backend.domain.member.MemberRepository;
import com.gdsc.pknu.backend.domain.member.Role;
import com.gdsc.pknu.backend.service.MemberService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
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.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@WebMvcTest(MemberRestController.class)
class MemberRestControllerTest {

@Autowired
MockMvc mvc;

@MockBean
MemberService memberService;

@MockBean
Jwt jwt;

@Test
@DisplayName("MemberRestControllerTest")
void 회원가입_테스트() throws Exception {
// given
RegisterRequest reg = RegisterRequest.builder()
.email("[email protected]")
.password("asdfgdsc")
.name("최정은")
.studentNumber("202012345")
.majorId(1L)
.phoneNumber("01012345678")
.generation(1)
.imagePath("asdfghjk")
.githubUrl("pkgdsc123")
.build();

Member member = Member.builder()
.email(new Email(reg.getEmail()))
.id(1L)
.password(reg.getPassword())
.studentNumber(reg.getStudentNumber())
.name(reg.getName())
.phoneNumber(reg.getPhoneNumber())
.majorId(reg.getMajorId())
.imagePath(reg.getImagePath())
.githubUrl(reg.getGithubUrl())
.build();

String token = member.generateApiToken(jwt, new String[]{"ROLE_USER"});

// when
ApiRes apiRes = ApiRes.SUCCESS(new RegisterResult(new MemberDto(member), token));

// then
assertEquals(true, apiRes.isSuccess());
Comment on lines +75 to +79
Copy link
Member

Choose a reason for hiding this comment

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

테스트하려는건 controller의 register함수 아닌가요? 여기서는 apiRes에 대한 테스트가 진행되네요!

Copy link
Author

Choose a reason for hiding this comment

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

아아 그러네요!! 다시 수정하도록 하겠습니다. 감사합니다!


// // given
// RegisterRequest reg = RegisterRequest.builder()
// .email("[email protected]")
// .password("asdfgdsc")
// .name("최정은")
// .studentNumber("202012345")
// .majorId(1L)
// .phoneNumber("01012345678")
// .generation(1)
// .imagePath("asdfghjk")
// .githubUrl("pkgdsc123")
// .build();
// Gson gson = new GsonBuilder().create();
// String registerRequest = gson.toJson(reg);
//
// // when
// this.mvc.perform(post("/")
// .contentType(MediaType.MULTIPART_FORM_DATA)
// .content(registerRequest))
// // then
// .andExpect(jsonPath("success", true).exists());
Comment on lines +96 to +101
Copy link
Member

Choose a reason for hiding this comment

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

여기서 andExpect 메서드를 perform의 꼬리에 붙이는게 맞나요? post의 꼬리에 붙이는건 아닌가요?

그리고 테스트가 실패했다면 테스트 코드가 아니라 컨트롤러 로직이 틀렸을 수도 있겠네요~

Copy link
Author

Choose a reason for hiding this comment

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

다른 코드 찾아보니 perform의 꼬리에 붙여두긴 하는데 다시 찾아봐야겠네요 감사합니다!!!

Copy link
Contributor

Choose a reason for hiding this comment

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

.contentType("application/json") 과 같은 메서드는 post의 꼬리에 붙이는게 맞고, andExpect의 경우 perform의 꼬리에 붙이는게 맞는거 같네요. post 꼬리에 붙일 경우 에러나더라구요

}
}
16 changes: 16 additions & 0 deletions src/test/resources/application.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
cloud:
aws:
credentials:
secret-key: zv5BNLeXj9SMqxi5DJ0saQRYze9zGWWlGS/e0obb
Copy link
Member

Choose a reason for hiding this comment

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

secret-key를 노출시키지 않는 방법은 없을까요?
github action에서 yml파일에 token을 사용할 때에는
repository 세팅에서 token을 생성해두고
${{ secret.GITHUB_TOKEN }} 처럼 사용하긴 합니다.

Copy link
Author

Choose a reason for hiding this comment

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

네넵 감사합니다!

Copy link
Contributor

Choose a reason for hiding this comment

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

저도 지원님처럼 민감한 정보는 따로 저장하거나 gitignore처리를 해주시는게 좋을 것 같네요!

access-key: AKIAUDWVDN7CRA3S3IOO
s3:
bucket: gdscpknubucket
region:
static: ap-northeast-2
stack:
auto: 'false'
jwt:
header: Authorization
issuer: test
secretKey: dbUzAdBo/+T1eXO9B2d+eWRgRx/EhzZ1GVsgPRNsxkawSw7W93mRxr0C3cswHKw0np03mLiqNgoJClH0XulECg==
algorithm: "HS256"