DataJpaTest 에서 Auditing

wellbeing-dough·2023년 11월 26일
1
post-thumbnail

1. 문제 상황

repository 단위 테스트 작성 중

@RepositoryTest
@ActiveProfiles("dev")
class CommentRepositoryTest {

    @Autowired
    private CommentRepository commentRepository;

    @Test
    void 게시글과_유저의_식별자로_댓글을_조회한다() {
        // given
        Long userId = 1L;
        Long postId = 3L;
        CommentEntity comment1 = CommentEntityFixture.COMMENT_1.commentEntity_생성(1L, userId, postId);
        CommentEntity comment2 = CommentEntityFixture.COMMENT_2.commentEntity_생성(2L, userId, postId);
        commentRepository.save(comment1);
        commentRepository.save(comment2);
        
        // when
        Pageable pageable = PageRequest.of(0, 10);
        Slice<CommentResponse> comments = commentRepository.findSliceByPostIdWithUserId(1L, userId, pageable);

        // then
        assertThat(comments.getContent()).hasSize(2);
        CommentResponse commentResponse1 = comments.getContent().get(1);
        CommentResponse commentResponse2 = comments.getContent().get(0);
        assertAll(
                () -> assertEquals(comment1.getId(), commentResponse1.getCommentId()),
                () -> assertEquals(comment1.getContent(), commentResponse1.getContent()),
                () -> assertEquals(comment2.getId(), commentResponse2.getCommentId()),
                () -> assertEquals(comment2.getContent(), commentResponse2.getContent())
        );
    }

}

이런 코드가 있는데 로컬에선 잘 되는데 CI배포 환경에서는 잘 안되었다

findSliceByPostIdWithUserId가 BaseTimeEntity에 createdDate로 최신순으로 정렬하는데 CI서버에서는 정렬이 안되는걸 확인할 수 있었다 로컬에서 commentResponse.getCreatedDate() 해보니 null이 떴다 그래서

@Getter
@EntityListeners(value = {AuditingEntityListener.class})
@MappedSuperclass
public abstract class BaseTimeEntity {
    // Entity가 생성되어 저장될 때 시간이 자동 저장됩니다.
    @CreatedDate
    @Column(name = "created_date")
    private LocalDateTime createdDate;

    // 조회한 Entity 값을 변경할 때 시간이 자동 저장됩니다.
    @LastModifiedDate
    @Column(name = "modified_date")
    private LocalDateTime modifiedDate;
}

여기에 SuperBuilder를 써서 직접 값을 넣게 해주려 했는데 그러면 테스트 코드를 짜기 위해서 본 메인 코드를 너무 건들이는 주객전도의 상황이 생기는거 같아서

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@AutoConfigureTestDatabase(replace = Replace.NONE)
@DataJpaTest(properties = {"spring.jpa.properties.hibernate.jdbc.time_zone=Asia/Seoul"})
@Import({TestQueryDslConfig.class, JpaAuditingConfig.class})
public @interface RepositoryTest {
}

그냥 테스트 설정에 JpaAuditionConfig.class 넣어줘서 해결했다

@Configuration
@EnableJpaAuditing
public class JpaAuditingConfig {
}

이생각을 왜 바로바로 못했지....

잘 돌아간다

0개의 댓글

관련 채용 정보