Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

테스트 코드 작성 환경 설정 #85

Merged
merged 15 commits into from
Apr 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package com.project.bumawiki.domain.docs.service;

import static org.assertj.core.api.AssertionsForClassTypes.*;
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.project.bumawiki.domain.docs.domain.Docs;
import com.project.bumawiki.domain.docs.domain.VersionDocs;
import com.project.bumawiki.domain.docs.domain.repository.DocsRepository;
import com.project.bumawiki.domain.docs.domain.repository.VersionDocsRepository;
import com.project.bumawiki.domain.docs.domain.type.DocsType;
import com.project.bumawiki.domain.user.domain.User;
import com.project.bumawiki.domain.user.domain.authority.Authority;
import com.project.bumawiki.domain.user.domain.repository.UserRepository;
import com.project.bumawiki.global.annotation.ServiceTest;

@ServiceTest
class CommandDocsServiceTest {

@Autowired
private UserRepository userRepository;
@Autowired
private CommandDocsService commandDocsService;
@Autowired
private DocsRepository docsRepository;
@Autowired
private VersionDocsRepository versionDocsRepository;

@Test
void 문서_생성하기() {
// given
User user = User.builder()
.email("[email protected]")
.name("마현우")
.enroll(2022)
.nickName("마현우")
.authority(Authority.USER)
.build();
userRepository.save(user);

String title = "제목";
String contents = "본문";
int enroll = 2024;
Docs docs = new Docs(title, enroll, DocsType.ACCIDENT);

// when
commandDocsService.create(docs, user, contents);

// then
assertThat(docsRepository.findByTitle(title).get().getTitle()).isEqualTo(title);
assertThat(versionDocsRepository.findFirstByDocsOrderByVersionDesc(docs).getContents()).isEqualTo(contents);
}

@Test
void 문서_업데이트하기() {
// given
User user = User.builder()
.email("[email protected]")
.name("마현우")
.enroll(2022)
.nickName("마현우")
.authority(Authority.USER)
.build();
userRepository.save(user);

String title = "제목";
String contents = "본문";
String updatedContents = "본문본문";
int enroll = 2024;
Docs docs = new Docs(title, enroll, DocsType.ACCIDENT);
commandDocsService.create(docs, user, contents);

// when
commandDocsService.update(user, title, updatedContents, 0);

// then
VersionDocs versionDocs = versionDocsRepository.findFirstByDocsOrderByVersionDesc(docs);
assertThat(versionDocs.getContents()).isEqualTo(updatedContents);
assertThat(versionDocs.getVersion()).isEqualTo(1);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.project.bumawiki.global.annotation;

import org.junit.jupiter.api.DisplayNameGeneration;
import org.junit.jupiter.api.DisplayNameGenerator;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

@Target(TYPE)
@Retention(RUNTIME)
@Transactional
@SpringBootTest
@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
public @interface ServiceTest {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오 항상 추상클래스로 구현 받아왔는데, 인터페이스로 처리하는 것도 좋네요!!

}
34 changes: 34 additions & 0 deletions src/test/java/com/project/bumawiki/global/truncate/Truncate.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.project.bumawiki.global.truncate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Component
public class Truncate {
@Autowired
private JdbcTemplate jdbcTemplate;

@Transactional
public void beforeEach() {
final List<String> truncateQueries = getTruncateQueries(jdbcTemplate);
execute(jdbcTemplate, "SET REFERENTIAL_INTEGRITY FALSE");
truncateTables(jdbcTemplate, truncateQueries);
execute(jdbcTemplate, "SET REFERENTIAL_INTEGRITY TRUE");
}

private List<String> getTruncateQueries(final JdbcTemplate jdbcTemplate) {
return jdbcTemplate.queryForList("SELECT Concat('TRUNCATE TABLE ', TABLE_NAME, ' RESTART IDENTITY;') AS q FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'PUBLIC'", String.class);
}

private void truncateTables(final JdbcTemplate jdbcTemplate, final List<String> truncateQueries) {
truncateQueries.forEach(v -> execute(jdbcTemplate, v));
}

private void execute(final JdbcTemplate jdbcTemplate, final String query) {
jdbcTemplate.execute(query);
}
}
Comment on lines +16 to +34
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이거의 전체 흐름을 설명해주세요

Copy link
Member Author

@NameIsUser06 NameIsUser06 Apr 16, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

truncate 처리를 코드에서 진행하기 위한 함수입니다

  • 먼저 REFERENTIAL_INTEGRITY는 외래키 제약조건 설정입니다.
  1. 테이블을 순서에 상관없이 truncate 하기 위해 끈 상태에서
  2. INFORMATION_SCHEMA.TABLES라는 곳에서 테이블 이름을 모두 가져옵니다
  3. 그 테이블 이름을 가져옴과 동시에 TRUNCATE TABLE TABLE_NAME RESTART IDENTITY 라는 문자열 형태로 가져옵니다
  4. forEach 형태를 통해 각 테이블 truncate를 실행합니다
  5. 다시 외래키 제약조건을 켭니다

위와같은 형태로 테이블 개수에 상관없이 모든 테이블을 truncate하는 것을 코드 형태로 작성된 클래스입니다

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

굳굳!

30 changes: 15 additions & 15 deletions src/test/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
spring:
datasource:
url: jdbc:h2:mem:test
url: jdbc:h2:mem:test;MODE=MYSQL;NON_KEYWORDS=USER
driverClassName: org.h2.Driver
username: sa
password:
Expand All @@ -14,7 +14,7 @@ spring:

jpa:
hibernate:
ddl-auto: create-drop
ddl-auto: create
database-platform: org.hibernate.dialect.H2Dialect
generate-ddl: true

Expand All @@ -23,6 +23,7 @@ spring:
org:
hibernate:
SQL: debug
show-sql: true

servlet:
multipart:
Expand All @@ -35,25 +36,24 @@ decorator:
p6spy:
enable-logging: true

auth:
jwt:
header: Authorization
secret: whfioydwfgiyodsgfionuasnfiuodsoiweqngfbkcjbwbdgfxhghfxjyuafgxasdfxyuyxfgqweiyrxftyqoifxyqiqwoixfniwoeqxfeiwunfxgiweuhfwqihwkefxhiwhfiuxnewhnfouxw
accessExp: 1800
refreshExp: 2592000
prefix: Bearer
jwt:
header: Authorization
secret: whfioydwfgiyodsgfionuasnfiuodsoiweqngfbkcjbwbdgfxhghfxjyuafgxasdfxyuyxfgqweiyrxftyqoifxyqiqwoixfniwoeqxfeiwunfxgiweuhfwqihwkefxhiwhfiuxnewhnfouxw
accessExp: 1800
refreshExp: 2592000
prefix: Bearer

bsm:
client-id: ${BSM_CLIENT_ID}
secret-key: ${BSM_SECRET_KEY}
redirect-url: ${BSM_REDIRECT_URL}
client-id: test-bsm-client-id
secret-key: test-bsm-client-secret
redirect-url: test-redirect-uri

#S3
aws:
s3:
bucket: ${S3_BUCKET}
access-key: ${S3_ACCESSKEY}
secret-key: ${S3_SECRET}
bucket: test-bucket
access-key: test-access-key
secret-key: test-secret-key

server:
port: 8080
Loading