From 69b942ea7dd363106be52e48b767e995d017d2ca Mon Sep 17 00:00:00 2001 From: geneaky Date: Wed, 18 Sep 2024 22:25:31 +0900 Subject: [PATCH] test: refactor test --- .../service/ChatServiceConcurrentTest.java | 2 +- .../repository/UserEntityRepositoryTest.java | 276 +++++++++--------- .../domain/user/service/UserServiceTest.java | 4 +- .../bookchat/support/RateLimiterAopTest.java | 3 +- .../bookchat/support/RateLimiterTest.java | 130 ++++----- .../support/RepositorySupportTest.java | 3 +- 6 files changed, 208 insertions(+), 210 deletions(-) diff --git a/src/test/java/toy/bookchat/bookchat/domain/chat/service/ChatServiceConcurrentTest.java b/src/test/java/toy/bookchat/bookchat/domain/chat/service/ChatServiceConcurrentTest.java index 2f823d26..7d8ab8bc 100644 --- a/src/test/java/toy/bookchat/bookchat/domain/chat/service/ChatServiceConcurrentTest.java +++ b/src/test/java/toy/bookchat/bookchat/domain/chat/service/ChatServiceConcurrentTest.java @@ -1,7 +1,7 @@ package toy.bookchat.bookchat.domain.chat.service; import static org.assertj.core.api.Assertions.assertThat; -import static toy.bookchat.bookchat.domain.common.Status.ACTIVE; +import static toy.bookchat.bookchat.support.Status.ACTIVE; import static toy.bookchat.bookchat.domain.participant.ParticipantStatus.HOST; import java.time.LocalDate; diff --git a/src/test/java/toy/bookchat/bookchat/domain/user/repository/UserEntityRepositoryTest.java b/src/test/java/toy/bookchat/bookchat/domain/user/repository/UserEntityRepositoryTest.java index d505c4d8..7cfe33e1 100644 --- a/src/test/java/toy/bookchat/bookchat/domain/user/repository/UserEntityRepositoryTest.java +++ b/src/test/java/toy/bookchat/bookchat/domain/user/repository/UserEntityRepositoryTest.java @@ -2,7 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static toy.bookchat.bookchat.domain.common.Status.ACTIVE; +import static toy.bookchat.bookchat.support.Status.ACTIVE; import java.util.Optional; import javax.persistence.EntityManager; @@ -17,144 +17,144 @@ class UserEntityRepositoryTest extends RepositoryTest { - @Autowired - private UserRepository userRepository; - @Autowired - private EntityManager em; + @Autowired + private UserRepository userRepository; + @Autowired + private EntityManager em; - @Test - void 사용자_이메일_OAuth2Provider를_구분으로_조회_성공() throws Exception { - - UserEntity userEntity1 = UserEntity.builder() - .name("user") - .email("kaktus418@gmail.com") - .provider(OAuth2Provider.KAKAO) - .build(); - - UserEntity userEntity2 = UserEntity.builder() - .name("user") - .email("kaktus418@gmail.com") - .provider(OAuth2Provider.GOOGLE) - .build(); - - userRepository.save(userEntity1); - userRepository.save(userEntity2); - - Optional kakaoUser = userRepository.findByEmailAndProvider( - "kaktus418@gmail.com", OAuth2Provider.KAKAO); - - Optional googleUser = userRepository.findByEmailAndProvider( - "kaktus418@gmail.com", OAuth2Provider.GOOGLE); - - assertThat(kakaoUser).isNotEqualTo(googleUser); - } - - @Test - void 사용자_nickname_존재시_true_반환_성공() throws Exception { - UserEntity userEntity = UserEntity.builder() - .name("user") - .email("kaktus418@gmail.com") - .provider(OAuth2Provider.KAKAO) - .nickname("nickname") - .build(); - - userRepository.save(userEntity); - - boolean result = userRepository.existsByNickname("nickname"); - - assertThat(result).isTrue(); - } - - @Test - void 사용자_nickname_존재하지않을시_false_반환_성공() throws Exception { - boolean result = userRepository.existsByNickname("nickname"); - - assertThat(result).isFalse(); - } - - @Test - void 사용자_이름으로_조회_성공() throws Exception { - String userName = "KAKAO123456"; - UserEntity userEntity = UserEntity.builder() - .name(userName) - .email("kaktus418@gmail.com") - .provider(OAuth2Provider.KAKAO) - .nickname("nickname") - .build(); - - userRepository.save(userEntity); - - UserEntity findUserEntity = userRepository.findByName(userName).get(); - - assertThat(userEntity).isEqualTo(findUserEntity); - } - - @Test - void 사용자_삭제_성공() throws Exception { - UserEntity userEntity = UserEntity.builder() - .email("test@gmail.com") - .name("testkakao") - .nickname("nickname") - .role(ROLE.USER) - .profileImageUrl("somethingImageUrl@naver.com") - .defaultProfileImageType(1) - .build(); - - userRepository.save(userEntity); - - userRepository.delete(userEntity); - - Optional ou = userRepository.findById(userEntity.getId()); - assertThat(ou).isNotPresent(); - } - - @Test - void 변경_요청한_닉네임_이미_있을시_예외발생() throws Exception { - UserEntity userEntity1 = UserEntity.builder() - .nickname("user1") - .build(); - - UserEntity userEntity2 = UserEntity.builder() - .nickname("user2") - .build(); - - userRepository.saveAndFlush(userEntity1); - userRepository.save(userEntity2); - userEntity2.changeUserNickname("user1"); - - assertThatThrownBy(() -> { - userRepository.flush(); - }).isInstanceOf(DataIntegrityViolationException.class); - } - - @Test - void 이미_존재하는_nickname인_경우_생성_실패() throws Exception { - UserEntity userEntity1 = UserEntity.builder() - .nickname("test nickname") - .build(); - - userRepository.save(userEntity1); + @Test + void 사용자_이메일_OAuth2Provider를_구분으로_조회_성공() throws Exception { + + UserEntity userEntity1 = UserEntity.builder() + .name("user") + .email("kaktus418@gmail.com") + .provider(OAuth2Provider.KAKAO) + .build(); + + UserEntity userEntity2 = UserEntity.builder() + .name("user") + .email("kaktus418@gmail.com") + .provider(OAuth2Provider.GOOGLE) + .build(); + + userRepository.save(userEntity1); + userRepository.save(userEntity2); + + Optional kakaoUser = userRepository.findByEmailAndProvider( + "kaktus418@gmail.com", OAuth2Provider.KAKAO); + + Optional googleUser = userRepository.findByEmailAndProvider( + "kaktus418@gmail.com", OAuth2Provider.GOOGLE); + + assertThat(kakaoUser).isNotEqualTo(googleUser); + } + + @Test + void 사용자_nickname_존재시_true_반환_성공() throws Exception { + UserEntity userEntity = UserEntity.builder() + .name("user") + .email("kaktus418@gmail.com") + .provider(OAuth2Provider.KAKAO) + .nickname("nickname") + .build(); + + userRepository.save(userEntity); + + boolean result = userRepository.existsByNickname("nickname"); + + assertThat(result).isTrue(); + } + + @Test + void 사용자_nickname_존재하지않을시_false_반환_성공() throws Exception { + boolean result = userRepository.existsByNickname("nickname"); + + assertThat(result).isFalse(); + } + + @Test + void 사용자_이름으로_조회_성공() throws Exception { + String userName = "KAKAO123456"; + UserEntity userEntity = UserEntity.builder() + .name(userName) + .email("kaktus418@gmail.com") + .provider(OAuth2Provider.KAKAO) + .nickname("nickname") + .build(); + + userRepository.save(userEntity); + + UserEntity findUserEntity = userRepository.findByName(userName).get(); + + assertThat(userEntity).isEqualTo(findUserEntity); + } + + @Test + void 사용자_삭제_성공() throws Exception { + UserEntity userEntity = UserEntity.builder() + .email("test@gmail.com") + .name("testkakao") + .nickname("nickname") + .role(ROLE.USER) + .profileImageUrl("somethingImageUrl@naver.com") + .defaultProfileImageType(1) + .build(); + + userRepository.save(userEntity); + + userRepository.delete(userEntity); + + Optional ou = userRepository.findById(userEntity.getId()); + assertThat(ou).isNotPresent(); + } + + @Test + void 변경_요청한_닉네임_이미_있을시_예외발생() throws Exception { + UserEntity userEntity1 = UserEntity.builder() + .nickname("user1") + .build(); + + UserEntity userEntity2 = UserEntity.builder() + .nickname("user2") + .build(); + + userRepository.saveAndFlush(userEntity1); + userRepository.save(userEntity2); + userEntity2.changeUserNickname("user1"); + + assertThatThrownBy(() -> { + userRepository.flush(); + }).isInstanceOf(DataIntegrityViolationException.class); + } + + @Test + void 이미_존재하는_nickname인_경우_생성_실패() throws Exception { + UserEntity userEntity1 = UserEntity.builder() + .nickname("test nickname") + .build(); + + userRepository.save(userEntity1); - UserEntity userEntity2 = UserEntity.builder() - .nickname("test nickname") - .build(); - assertThatThrownBy(() -> userRepository.save(userEntity2)) - .isInstanceOf(DataIntegrityViolationException.class); - } - - @Test - void 사용자_계정생성시_기본_상태값_active로_생성_성공() throws Exception { - UserEntity userEntity = UserEntity.builder() - .nickname("user1") - .build(); - - userRepository.save(userEntity); - - em.flush(); - em.clear(); - - UserEntity findUserEntity = userRepository.findById(userEntity.getId()).get(); + UserEntity userEntity2 = UserEntity.builder() + .nickname("test nickname") + .build(); + assertThatThrownBy(() -> userRepository.save(userEntity2)) + .isInstanceOf(DataIntegrityViolationException.class); + } + + @Test + void 사용자_계정생성시_기본_상태값_active로_생성_성공() throws Exception { + UserEntity userEntity = UserEntity.builder() + .nickname("user1") + .build(); + + userRepository.save(userEntity); + + em.flush(); + em.clear(); + + UserEntity findUserEntity = userRepository.findById(userEntity.getId()).get(); - assertThat(findUserEntity.getStatus()).isEqualTo(ACTIVE); - } + assertThat(findUserEntity.getStatus()).isEqualTo(ACTIVE); + } } \ No newline at end of file diff --git a/src/test/java/toy/bookchat/bookchat/domain/user/service/UserServiceTest.java b/src/test/java/toy/bookchat/bookchat/domain/user/service/UserServiceTest.java index 054ad7e7..53888666 100644 --- a/src/test/java/toy/bookchat/bookchat/domain/user/service/UserServiceTest.java +++ b/src/test/java/toy/bookchat/bookchat/domain/user/service/UserServiceTest.java @@ -10,7 +10,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.internal.verification.VerificationModeFactory.noInteractions; -import static toy.bookchat.bookchat.domain.common.Status.ACTIVE; +import static toy.bookchat.bookchat.support.Status.ACTIVE; import java.util.Optional; import org.junit.jupiter.api.DisplayName; @@ -24,7 +24,7 @@ import toy.bookchat.bookchat.db_module.device.repository.DeviceRepository; import toy.bookchat.bookchat.db_module.user.UserEntity; import toy.bookchat.bookchat.db_module.user.repository.UserRepository; -import toy.bookchat.bookchat.domain.common.Status; +import toy.bookchat.bookchat.support.Status; import toy.bookchat.bookchat.domain.storage.StorageService; import toy.bookchat.bookchat.domain.user.UserProfile; import toy.bookchat.bookchat.domain.user.api.v1.request.ChangeUserNicknameRequest; diff --git a/src/test/java/toy/bookchat/bookchat/support/RateLimiterAopTest.java b/src/test/java/toy/bookchat/bookchat/support/RateLimiterAopTest.java index f4c2cfd1..8111f7c2 100644 --- a/src/test/java/toy/bookchat/bookchat/support/RateLimiterAopTest.java +++ b/src/test/java/toy/bookchat/bookchat/support/RateLimiterAopTest.java @@ -1,10 +1,9 @@ -package toy.bookchat.bookchat.domain.common; +package toy.bookchat.bookchat.support; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.springframework.aop.aspectj.AspectJExpressionPointcut; -import toy.bookchat.bookchat.support.RateLimit; class RateLimiterAopTest { diff --git a/src/test/java/toy/bookchat/bookchat/support/RateLimiterTest.java b/src/test/java/toy/bookchat/bookchat/support/RateLimiterTest.java index 2cf903eb..5a131853 100644 --- a/src/test/java/toy/bookchat/bookchat/support/RateLimiterTest.java +++ b/src/test/java/toy/bookchat/bookchat/support/RateLimiterTest.java @@ -1,4 +1,4 @@ -package toy.bookchat.bookchat.domain.common; +package toy.bookchat.bookchat.support; import static org.assertj.core.api.Assertions.assertThat; @@ -18,81 +18,81 @@ class RateLimiterTest { - @Test - @Disabled("bucket4j 학습 테스트") - void greedy_요청제한_테스트() throws Exception { - LocalBucket bucket = Bucket.builder() - //토큰 최대 2개 들고 있을 수 있는 버킷에서 - //5초에 1개씩 버켓이 생성될때 - .addLimit(Bandwidth.classic(2, Refill.greedy(2, Duration.ofSeconds(10)))) - .build(); + @Test + @Disabled("bucket4j 학습 테스트") + void greedy_요청제한_테스트() throws Exception { + LocalBucket bucket = Bucket.builder() + //토큰 최대 2개 들고 있을 수 있는 버킷에서 + //5초에 1개씩 버켓이 생성될때 + .addLimit(Bandwidth.classic(2, Refill.greedy(2, Duration.ofSeconds(10)))) + .build(); - int result = 0; - for (int i = 0; i < 3; i++) { - if (bucket.tryConsume(1)) { - result++; - } - Thread.sleep(2500); // 1,2번째 토큰을 뽑고 2.5초씩 2번 대기하면 총 5초가 지난뒤 토큰 하나가 채워짐 - } - - assertThat(result).isEqualTo(3); + int result = 0; + for (int i = 0; i < 3; i++) { + if (bucket.tryConsume(1)) { + result++; + } + Thread.sleep(2500); // 1,2번째 토큰을 뽑고 2.5초씩 2번 대기하면 총 5초가 지난뒤 토큰 하나가 채워짐 } - @Test - @Disabled("bucket4j 학습 테스트") - void interval_요청제한_테스트() throws Exception { - LocalBucket bucket = Bucket.builder() - //토큰 최대 2개 들고 있을 수 있는 버킷에서 - //10초 기다린 후 토큰 2개 생성됨 - .addLimit(Bandwidth.classic(2, Refill.intervally(2, Duration.ofSeconds(10)))) - .build(); + assertThat(result).isEqualTo(3); + } - int result = 0; + @Test + @Disabled("bucket4j 학습 테스트") + void interval_요청제한_테스트() throws Exception { + LocalBucket bucket = Bucket.builder() + //토큰 최대 2개 들고 있을 수 있는 버킷에서 + //10초 기다린 후 토큰 2개 생성됨 + .addLimit(Bandwidth.classic(2, Refill.intervally(2, Duration.ofSeconds(10)))) + .build(); - for (int i = 0; i < 4; i++) { - if (bucket.tryConsume(1)) { - result++; - } - if (i == 1) { //토큰 다 쓰고 10초 기달려야 다시 채워짐 - Thread.sleep(10000); - } - } + int result = 0; - assertThat(result).isEqualTo(4); + for (int i = 0; i < 4; i++) { + if (bucket.tryConsume(1)) { + result++; + } + if (i == 1) { //토큰 다 쓰고 10초 기달려야 다시 채워짐 + Thread.sleep(10000); + } } - @RepeatedTest(100) - @Disabled("bucket4j 학습 테스트") - void 멀티스레드_요청제한_테스트() throws Exception { - //기본전략 lock free >> 높은 race condition과 스레드가 서로 블로킹하지 않는다 - //synchronized >> race condition을 고려하지 않고 메모리 할당없이 사용 / 다른 스레드를 블로킹함 - // none >> 싱글스레드에서 사용하는 전략 >> 동시성 문제 발생 - LocalBucket bucket = Bucket.builder() - .addLimit( - Bandwidth.classic(100, Refill.greedy(1, Duration.ofSeconds(100)))) //토큰 50개가지고 테스트 - .withSynchronizationStrategy(SynchronizationStrategy.LOCK_FREE) - .build(); + assertThat(result).isEqualTo(4); + } - int THREAD_COUNT = 10; - ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT); - CountDownLatch latch = new CountDownLatch(300); - AtomicInteger result = new AtomicInteger(); - //동시성 문제가 발생한다면 결과가 300보다 작게나올것 - for (int i = 0; i < THREAD_COUNT; i++) { - //thread 10개에서 30개씩 토큰 받아서 카운트 - executorService.execute(() -> { - for (int j = 0; j < 30; j++) { - if (bucket.tryConsume(1)) { - result.addAndGet(1); - } - latch.countDown(); - } - }); - } - latch.await(); + @RepeatedTest(100) + @Disabled("bucket4j 학습 테스트") + void 멀티스레드_요청제한_테스트() throws Exception { + //기본전략 lock free >> 높은 race condition과 스레드가 서로 블로킹하지 않는다 + //synchronized >> race condition을 고려하지 않고 메모리 할당없이 사용 / 다른 스레드를 블로킹함 + // none >> 싱글스레드에서 사용하는 전략 >> 동시성 문제 발생 + LocalBucket bucket = Bucket.builder() + .addLimit( + Bandwidth.classic(100, Refill.greedy(1, Duration.ofSeconds(100)))) //토큰 50개가지고 테스트 + .withSynchronizationStrategy(SynchronizationStrategy.LOCK_FREE) + .build(); - assertThat(result.get()).isEqualTo(100); + int THREAD_COUNT = 10; + ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT); + CountDownLatch latch = new CountDownLatch(300); + AtomicInteger result = new AtomicInteger(); + //동시성 문제가 발생한다면 결과가 300보다 작게나올것 + for (int i = 0; i < THREAD_COUNT; i++) { + //thread 10개에서 30개씩 토큰 받아서 카운트 + executorService.execute(() -> { + for (int j = 0; j < 30; j++) { + if (bucket.tryConsume(1)) { + result.addAndGet(1); + } + latch.countDown(); + } + }); } + latch.await(); + + assertThat(result.get()).isEqualTo(100); + } } \ No newline at end of file diff --git a/src/test/java/toy/bookchat/bookchat/support/RepositorySupportTest.java b/src/test/java/toy/bookchat/bookchat/support/RepositorySupportTest.java index 2c190982..e579742e 100644 --- a/src/test/java/toy/bookchat/bookchat/support/RepositorySupportTest.java +++ b/src/test/java/toy/bookchat/bookchat/support/RepositorySupportTest.java @@ -1,4 +1,4 @@ -package toy.bookchat.bookchat.domain.common; +package toy.bookchat.bookchat.support; import static com.querydsl.core.types.PathMetadataFactory.forVariable; import static org.assertj.core.api.Assertions.assertThat; @@ -12,7 +12,6 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import toy.bookchat.bookchat.domain.RepositoryTest; -import toy.bookchat.bookchat.support.RepositorySupport; class RepositorySupportTest extends RepositoryTest {