-
Notifications
You must be signed in to change notification settings - Fork 4
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
base: main
Are you sure you want to change the base?
컨트롤러 테스트 코드 작성 #13
Conversation
…컨트롤러 테스트 코드 작성
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
mocking한 객체는 controller를 생성할 때 매개변수로 넣어줄 수 있어요.
또한 verify 메서드로 mock객체 내부 함수가 실행되었는지 체크하는 방법도 있습니다.
예시로 controller의 register를 실행시켰을 때 mockService의 register가 실행되었는지 체크할 수 있습니다~~
|
||
@Test | ||
@DisplayName("MemberRestControllerTest") | ||
void register() throws Exception { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
테스트 함수의 네이밍 컨벤션도 정하면 좋을 것 같아요.
개인적으로는 구체적으로 어떤 상황에 어떤 결과가 연출돼야 하는지 나타내는게 좋았습니다.
제가 시도해본 컨벤션들 세가지만 적어둘게요!
- 한글네이밍 ex)
등록할 때 테스트()
- 이건 junit5로 넘어가면서 DisplayName 어노테이션이 생겨서 여기 한글로 표시해도 좋을 것 같습니다.
${함수이름}Test_${When}_${Then}
ex)registerTest_regist_success()
- 어떤 함수를 테스트하고, 어떤 상황에서 어떤 결과가 나오는지를 나타냅니다.
when${ }_should${}
ex)whenRegistCorrect_shouldSuccess()
- 언제 어떤 결과가 나오는지를 나타냅니다.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
네넵 감사합니다!
// when | ||
ApiRes apiRes = ApiRes.SUCCESS(new RegisterResult(new MemberDto(member), token)); | ||
|
||
// then | ||
assertEquals(true, apiRes.isSuccess()); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
테스트하려는건 controller의 register함수 아닌가요? 여기서는 apiRes에 대한 테스트가 진행되네요!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
아아 그러네요!! 다시 수정하도록 하겠습니다. 감사합니다!
cloud: | ||
aws: | ||
credentials: | ||
secret-key: zv5BNLeXj9SMqxi5DJ0saQRYze9zGWWlGS/e0obb |
There was a problem hiding this comment.
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 }} 처럼 사용하긴 합니다.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
네넵 감사합니다!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
저도 지원님처럼 민감한 정보는 따로 저장하거나 gitignore처리를 해주시는게 좋을 것 같네요!
// // when | ||
// this.mvc.perform(post("/") | ||
// .contentType(MediaType.MULTIPART_FORM_DATA) | ||
// .content(registerRequest)) | ||
// // then | ||
// .andExpect(jsonPath("success", true).exists()); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
여기서 andExpect 메서드를 perform의 꼬리에 붙이는게 맞나요? post의 꼬리에 붙이는건 아닌가요?
그리고 테스트가 실패했다면 테스트 코드가 아니라 컨트롤러 로직이 틀렸을 수도 있겠네요~
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
다른 코드 찾아보니 perform의 꼬리에 붙여두긴 하는데 다시 찾아봐야겠네요 감사합니다!!!
There was a problem hiding this comment.
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 꼬리에 붙일 경우 에러나더라구요
// // when | ||
// this.mvc.perform(post("/") | ||
// .contentType(MediaType.MULTIPART_FORM_DATA) | ||
// .content(registerRequest)) | ||
// // then | ||
// .andExpect(jsonPath("success", true).exists()); |
There was a problem hiding this comment.
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 꼬리에 붙일 경우 에러나더라구요
src/main/resources/application.yml
Outdated
@@ -0,0 +1,18 @@ | |||
cloud: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
application.yml파일은 secret key, 비밀번호 등 민감한 정보를 저장하고 있어 gitignore에 등록하고 업로드 되지 않게 해야 합니다. AWS와 관련된 정보는 악의적인 사용으로 인해 추가적 과금까지도 이어질 수 있으니 주의해주세요
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
네넵 gitignore에 등록해뒀습니다! 감사합니다 :)
cloud: | ||
aws: | ||
credentials: | ||
secret-key: zv5BNLeXj9SMqxi5DJ0saQRYze9zGWWlGS/e0obb |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
저도 지원님처럼 민감한 정보는 따로 저장하거나 gitignore처리를 해주시는게 좋을 것 같네요!
@@ -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' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
junit 4로 쓰셨네요. 저는 5로 작업했는데, 논의 후에 통일해봐도 좋을 것 같아요
What is the PR?
Changes
Test Check List
etc
mock 객체를 이용하여 테스트 코드 작성 시, 에러가 발생하여 다음과 같은 방법으로 일단 구현해두었습니다.
RegisterRequest 객체 생성 후 이를 이용해 member 객체를 생성 -> token 생성 -> ApiRes.SUCCESS(new RegisterResult(new MemberDto(member), token)) -> apiRes.isSuccess()가 true와 같은지 확인
mock 객체 이용하여 작성한 코드 주석 처리 해두었는데 한번 봐주시면 감사하겠습니다!
발생 에러
MockHttpServletRequest:
HTTP Method = POST
Request URI = /
Parameters = {}
Headers = [Content-Type:"multipart/form-data;charset=UTF-8", Content-Length:"197"]
Body = {"email":"[email protected]","password":"asdfgdsc","name":"최정은","studentNumber":"202012345","majorId":1,"phoneNumber":"01012345678","generation":1,"imagePath":"asdfghjk","githubUrl":"pkgdsc123"}
Session Attrs = {}
Handler:
Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []