티스토리 뷰
이 게시글은 공부했던 내용을 기억하기 위한 포스팅입니다.
이 게시글은 공부했던 내용을 기록하기 위한 용도로, 옳지 않은 부분이 있을 수 있습니다.
틀린 부분이나 더 좋은 의견은 댓글로 공유 부탁드립니다.
시작
최근 강의를 보며 직접 따라 하며 학습하고 있다.
그 중 인상 깊었던 것은 강의 시간 대부분을 테스트 코드 작성 및 테스트 확인하는 데에 사용하였다.
테스트 코드를 잘 작성하면 그만큼 신뢰성 있는 서비스를 만들고, 생산성을 높일 수 있을 것 같다.
아래 코드는 그중 한 내용이다.
다음과 같은 테스트 소스코드가 있다.
mockMvc.perform(post("/posts")
.contentType(APPLICATION_JSON)
.content("{\"title\":\"게시글 제목\", \"content\":\"게시글 내용\"}")
)
.andExpect(status().isOk());
title, content를 json 형태로 만들어서 post 방식으로 요청하는 내용이다.
만약 파라미터가 백개라면?
일일이 json 형태로 작성하는것은 번거롭고, 생산성이 떨어진다.
따라서 json 형태를 직접 입력하기 보다 객체를 이용하여 json형태로 리턴해준다.
//given
Post request = new Post("글 제목", "글 내용");
ObjectMapper objectMapper = new ObjectMapper();
String requestJson = objectMapper.writeValueAsString(request);
//EXPECTED
mockMvc.perform(post("/posts")
.contentType(APPLICATION_JSON)
.content(requestJson)
) //application/json
.andExpect(status().isOk())
Post 객체를 생성하고, 다음과 같이 생성자를 통해 title, content를 넣어준다.
그 후 ObjectMapper를 이용하여 json 형태로 변환한다.(ObjectMapper도 나중에 공부 해봐야한다..)
문제는 파라미터가 많을 경우, (마찬가지로) 매번 생성자를 생성하고 모든 파라미터를 넣는것은 비효율적이다.
따라서 lombock의 @builder를 이용하면 다음과 같이 작성 가능하다.
Post request = Post.builder()
.title("글 제목")
.content("글 내용")
.build();
ObjectMapper objectMapper = new ObjectMapper();
String requestJson = objectMapper.writeValueAsString(request);
Post객체 소스코드
import lombok.*;
import javax.persistence.*;
@Entity
@NoArgsConstructor
@Getter
@Setter
public class Post {
@Builder
public Post(String title, String content) {
this.title = title;
this.content = content;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@Lob
private String content;
}
@Builder 어노테이션을 통해 만들어진 소스코드(build 경로에서 본 class 파일)
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
@Entity
public class Post {
@Id
@GeneratedValue(
strategy = GenerationType.IDENTITY
)
private Long id;
private String title;
@Lob
private String content;
public Post(String title, String content) {
this.title = title;
this.content = content;
}
public static PostBuilder builder() {
return new PostBuilder();
}
public Post() {
}
public Long getId() {
return this.id;
}
public String getTitle() {
return this.title;
}
public String getContent() {
return this.content;
}
public void setId(final Long id) {
this.id = id;
}
public void setTitle(final String title) {
this.title = title;
}
public void setContent(final String content) {
this.content = content;
}
public static class PostBuilder {
private String title;
private String content;
PostBuilder() {
}
public PostBuilder title(final String title) {
this.title = title;
return this;
}
public PostBuilder content(final String content) {
this.content = content;
return this;
}
public Post build() {
return new Post(this.title, this.content);
}
public String toString() {
return "Post.PostBuilder(title=" + this.title + ", content=" + this.content + ")";
}
}
}
생성자에 @Builder 어노테이션을 주면 다음과 같이 내부적으로 static Builder클래스와 생성자를 자동으로 생성하는것을 알 수 있다.
@Builder 어노테이션 사용 장점
- 코드 간결성
- 생성자 오버라이딩 불필요 / 원하는 value값을 선택할 수 있음.
@Builder 어노테이션 사용 단점
- 코드 복잡성 증가
결론
@Builder 어노테이션을 이용하여 테스트 코드를 간결하게 짤 수 있었고, intelliJ를 이용하여 컴파일된 class파일을 확인하는 방법도 알 수 있었다.
구글링하여 찾은 소스코드를 맹목적으로 적용하는것이 아닌, 내부 동작원리를 파악하는 노력을 통해 발전할 수 있을것 같다.
참고
https://velog.io/@park2348190/Lombok-Builder%EC%9D%98-%EB%8F%99%EC%9E%91-%EC%9B%90%EB%A6%AC
https://projectlombok.org/features/Builder
@Builder
projectlombok.org
https://projectlombok.org/api/lombok/Builder
Builder (Lombok)
The builder annotation creates a so-called 'builder' aspect to the class that is annotated or the class that contains a member which is annotated with @Builder. If a member is annotated, it must be either a constructor or a method. If a class is annotated,
projectlombok.org
https://pplenty.tistory.com/13
[intelliJ] lombok 생성 코드 확인하기
왜 lombok 을 사용할까? 롬복(lombok)의 동작원리는 간단하게 말해 컴파일 시점에 바이트 코드를 변환하여 원하는 부분을 주입해주는 방식이다. 때문에 우린 Getter, Setter, Constructor 등을 롬복 어노테
pplenty.tistory.com
💠 빌더(Builder) 패턴 - 완벽 마스터하기
Builder Pattern 빌더 패턴(Builder Pattern)은 복잡한 객체의 생성 과정과 표현 방법을 분리하여 다양한 구성의 인스턴스를 만드는 생성 패턴이다. 생성자에 들어갈 매개 변수를 메서드로 하나하나 받아
inpa.tistory.com
정말 간결하게 잘 설명되어 있는글이다..
'BACK > SPRING+JPA' 카테고리의 다른 글
Request DTO default Value 설정하기 (1) | 2024.01.30 |
---|
- Total
- Today
- Yesterday
- 주사위게임3
- level1
- 명시적 초기화
- vue3
- 다음 큰 숫자
- python2.7
- Leve2
- Level2
- JAVA 변수 초기화
- vue3란?
- composition api
- Mac
- builder
- vue정의
- 초기화블럭
- 인스턴스초기화블럭
- python3
- 클래스초기화블럭
- 문제 리포트
- spring
- 프로그래머스
- optionsAPI
- JadenCase
- Java
- 괄호 회전하기
- defaultdict
- LELVE1
- 숫자의표현
- collections
- 문자열만들기
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |