Skip to content

Commit

Permalink
feat: 테스트 코드 격리 (#84)
Browse files Browse the repository at this point in the history
* feat: 테스트 코드 격리

* fix: 중복 gradle 수정

* fix: guava 의존성 해제

* fix: guava 원복

* fix: DatabaseCleaner Service -> Component

* fix: unwrap 이슈로 해결 및 guava 의존성 해제
  • Loading branch information
char-yb authored Dec 30, 2023
1 parent 933f1c2 commit b919b8d
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/test/java/com/depromeet/DatabaseCleaner.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.depromeet;

import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.stream.Collectors;
import org.hibernate.Session;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

@Component
public class DatabaseCleaner implements InitializingBean {

@PersistenceContext private EntityManager entityManager;
private List<String> tableNames;

@Override
public void afterPropertiesSet() {
entityManager.unwrap(Session.class).doWork(this::extractTableNames);
}

private void extractTableNames(Connection conn) {
tableNames =
entityManager.getMetamodel().getEntities().stream()
.map(e -> e.getName().replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase())
.collect(Collectors.toList());
}

public void execute() {
entityManager.unwrap(Session.class).doWork(this::cleanUpDatabase);
}

private void cleanUpDatabase(Connection conn) throws SQLException {
Statement statement = conn.createStatement();
statement.executeUpdate("SET REFERENTIAL_INTEGRITY FALSE");

for (String tableName : tableNames) {
statement.executeUpdate("TRUNCATE TABLE " + tableName);
statement.executeUpdate(
"ALTER TABLE "
+ tableName
+ " ALTER COLUMN "
+ tableName
+ "_id RESTART WITH 1");
}

statement.executeUpdate("SET REFERENTIAL_INTEGRITY TRUE");
}
}

0 comments on commit b919b8d

Please sign in to comment.