Skip to content

Commit

Permalink
♻️ [Refactor] 테스트 설정 및 기본 테스트 코드 작성
Browse files Browse the repository at this point in the history
  • Loading branch information
Eunjin3395 committed Aug 15, 2024
1 parent 54fc7a6 commit 9bc151e
Show file tree
Hide file tree
Showing 5 changed files with 280 additions and 0 deletions.
28 changes: 28 additions & 0 deletions .github/workflows/pr-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: PR Test

on:
pull_request:
branches: [ develop ] # develop branch에 PR을 보낼 때 실행
push:
branches:
- refactor/171

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3

- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'

# Gradle wrapper 파일 실행 권한주기
- name: Grant execute permission for gradlew
run: chmod +x gradlew

# Gradle test를 실행
- name: Test with Gradle
run: ./gradlew --info test
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ dependencies {
annotationProcessor "jakarta.persistence:jakarta.persistence-api"
// java.lang.NoClassDefFoundError (javax.annotation.Entity) 대응 코드

testRuntimeOnly("com.h2database:h2")


}

tasks.named('test') {
Expand Down
110 changes: 110 additions & 0 deletions src/test/java/com/gamegoo/chat/ChatServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package com.gamegoo.chat;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.gamegoo.domain.chat.Chatroom;
import com.gamegoo.domain.chat.MemberChatroom;
import com.gamegoo.domain.member.LoginType;
import com.gamegoo.domain.member.Member;
import com.gamegoo.dto.chat.ChatResponse.ChatroomEnterDTO;
import com.gamegoo.repository.chat.ChatroomRepository;
import com.gamegoo.repository.chat.MemberChatroomRepository;
import com.gamegoo.repository.member.MemberRepository;
import com.gamegoo.service.chat.ChatCommandService;
import java.util.ArrayList;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;

@SpringBootTest
@Transactional
public class ChatServiceTest {

@Autowired
private ChatCommandService chatCommandService;

@Autowired
private MemberRepository memberRepository;

@Autowired
private ChatroomRepository chatroomRepository;

@Autowired
private MemberChatroomRepository memberChatroomRepository;

private Member member1;

private Member member2;

@BeforeEach
public void setUp() {
// 기본 테스트에 사용할 멤버 객체를 미리 생성
int randomProfileImage = ThreadLocalRandom.current().nextInt(1, 9);
member1 = Member.builder()
.id(1L)
.email("[email protected]")
.password("12345678")
.loginType(LoginType.GENERAL)
.profileImage(randomProfileImage)
.blind(false)
.mike(false)
.mannerLevel(1)
.isAgree(true)
.blockList(new ArrayList<>())
.memberChatroomList(new ArrayList<>())
.build();

member2 = Member.builder()
.id(2L)
.email("[email protected]")
.password("12345678")
.loginType(LoginType.GENERAL)
.profileImage(randomProfileImage)
.blind(false)
.mike(false)
.mannerLevel(1)
.isAgree(true)
.blockList(new ArrayList<>())
.memberChatroomList(new ArrayList<>())
.build();

member1 = memberRepository.save(member1);
member2 = memberRepository.save(member2);
}

@Test
@DisplayName("특정 회원과 채팅방 시작, 기존에 채팅방 없는 경우 - 성공")
public void successStartChatroomByMemberIdAndCreateNewChatroom() throws Exception {
// when
ChatroomEnterDTO chatroomEnterDTO = chatCommandService.startChatroomByMemberId(
member1.getId(), member2.getId());

// then
// 1. ChatroomEnterDTO의 값 검증
assertNotNull(chatroomEnterDTO);
assertEquals(member2.getId(), chatroomEnterDTO.getMemberId());

// 2. 데이터베이스에서 채팅방이 실제로 생성되었는지 검증
Optional<Chatroom> createdChatroom = chatroomRepository.findByUuid(
chatroomEnterDTO.getUuid());
assertTrue(createdChatroom.isPresent());

// 3. MemberChatroom 엔티티가 각 회원에 대해 잘 생성되었는지 검증
Optional<MemberChatroom> member1Chatroom = memberChatroomRepository.findByMemberIdAndChatroomId(
member1.getId(), createdChatroom.get().getId());
Optional<MemberChatroom> member2Chatroom = memberChatroomRepository.findByMemberIdAndChatroomId(
member2.getId(), createdChatroom.get().getId());

assertTrue(member1Chatroom.isPresent());
assertTrue(member2Chatroom.isPresent());
}


}
102 changes: 102 additions & 0 deletions src/test/java/com/gamegoo/member/ProfileServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package com.gamegoo.member;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;

import com.gamegoo.apiPayload.code.status.ErrorStatus;
import com.gamegoo.apiPayload.exception.GeneralException;
import com.gamegoo.domain.member.LoginType;
import com.gamegoo.domain.member.Member;
import com.gamegoo.repository.member.MemberRepository;
import com.gamegoo.service.member.ProfileService;
import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;

@SpringBootTest
@Transactional
public class ProfileServiceTest {

@Autowired
private ProfileService profileService;

@Autowired
private MemberRepository memberRepository;

private Member member1;

private Member member2;

@BeforeEach
public void setUp() {
// 기본 테스트에 사용할 멤버 객체를 미리 생성
int randomProfileImage = ThreadLocalRandom.current().nextInt(1, 9);
member1 = Member.builder()
.id(1L)
.email("[email protected]")
.password("12345678")
.loginType(LoginType.GENERAL)
.profileImage(randomProfileImage)
.blind(false)
.mike(false)
.mannerLevel(1)
.isAgree(true)
.blockList(new ArrayList<>())
.memberChatroomList(new ArrayList<>())
.build();

member2 = Member.builder()
.id(2L)
.email("[email protected]")
.password("12345678")
.loginType(LoginType.GENERAL)
.profileImage(randomProfileImage)
.blind(false)
.mike(false)
.mannerLevel(1)
.isAgree(true)
.blockList(new ArrayList<>())
.memberChatroomList(new ArrayList<>())
.build();

member1 = memberRepository.save(member1);
member2 = memberRepository.save(member2);
}


@Test
@DisplayName("memberId로 member 찾기 - 성공")
public void successFindMemberById() throws Exception {
// when
System.out.println("member1 = " + member1.getId());
Member testMember = profileService.findMember(member1.getId()); // 실제 서비스 호출

// then
assertNotNull(member1); // 결과가 null이 아님을 확인
assertEquals(member1.getId(), testMember.getId()); // ID 비교
assertEquals(member1.getEmail(), testMember.getEmail()); // 이메일 비교
}

@Test
@DisplayName("memberId로 member 찾기 - 실패")
public void failFindMemberById() throws Exception {
// given
Long nonExistentMemberId = -1L;
ErrorStatus expectedErrorCode = ErrorStatus.MEMBER_NOT_FOUND; // 기대하는 에러 코드

// when & then
GeneralException exception = assertThrows(GeneralException.class, () -> {
profileService.findMember(nonExistentMemberId);
});

// 발생한 예외의 code가 기대하는 값인지 확인
assertEquals(expectedErrorCode, exception.getCode());
}

}
37 changes: 37 additions & 0 deletions src/test/resources/application.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
spring:
datasource:
url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
driver-class-name: org.h2.Driver
username: sa
password:
h2:
console:
enabled: true # H2 콘솔 사용 가능
jpa:
hibernate:
ddl-auto: update
show-sql: true # SQL 로그 출력
# JWT Secret key 설정
jwt:
secret: secretsecretsecretsecretsecretsecretsecretsecretsecretsecretsecretsecretsecretsecretsecretsecretsecretsecret
#riot API 설정
riot:
api:
key: test-key

# Gmail 설정
mail:
host: smtp.gmail.com
port: 587
username: [email protected]
password: test-pwd
properties:
mail:
smtp:
auth: true
starttls:
enable: true

socket:
server:
url: http://localhost:3000

0 comments on commit 9bc151e

Please sign in to comment.