Domain Layer 객체인 User에 대해서 예시를 들어보겠습니다.
테스트를 위한 생성자로 default 접근 제어자와 @VisibleForTesting
을 기입하였습니다.
@Getter
@Entity
@Table(name = "users")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String email;
private String username;
@Builder
public User(String email, String username) {
this.email = email;
this.username = username;
}
@VisibleForTesting
User(Long id, String email, String username) {
this.id = id;
this.email = email;
this.username = username;
}
public class UserFixture {
private Long id = 1L;
private String email = "name@domain.com";
private String username = "username";
public static UserFixture aUser() {
return new UserFixture();
}
public UserFixture id(final Long id) {
this.id = id;
return this;
}
public UserFixture email(final String email) {
this.email = email;
return this;
}
public UserFixture username(final String username) {
this.username = username;
return this;
}
public User build() {
return new User(id, email, username);
}
}
위와 같이 도메인 객체에 대해서 Fixture를 만들어줌으로써 추후 많은 곳에서 기본 포맷을 가지는 UserFixture를 가질 수 있게 됩니다.
Fixture를 만들 때마다 수 많은 필드로부터 하나 하나 수작업을 해줘야 하는 단점이 있습니다.
해당 예시에 대해서 @Setter
/ @Builder
를 사용하고 조금의 작업을 해준다면 해결되는 문제겠지만,
직접 사용하는 클라이언트 입장에서 조금 불편한 코드가 될 수 있습니다.
@Accessors
다음과 같이 @Setter
와 @Accessors
를 사용하면 보다 편하게 Fixture를 생성할 수 있습니다!
@Setter
@Accessors(fluent = true, chain = true)
public class UserFixture {
private Long id = 1L;
private String email = "name@domain.com";
private String username = "username";
public static UserFixture aUser() {
return new UserFixture();
}
public User build() {
return new User(id, email, username);
}
}
그렇다면 @Accessors
의 옵션에는 무엇이 있는지 알아보겠습니다.
fluent
.setName()
→ name()
chain
return this
를 하여 체이닝 메서드로 사용할 수 있습니다.prefix
makeFinal