Skip to content

Commit

Permalink
refactor: testEventListener 에서 truncate 쿼리를 실행하여 데이터 초기화하도록 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
rimrim990 committed Aug 21, 2023
1 parent b1430b8 commit c1e6158
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 10 deletions.
7 changes: 0 additions & 7 deletions src/main/resources/clean.sql

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,8 @@
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.Sql.ExecutionPhase;

@ActiveProfiles("test")
@Sql(scripts = "classpath:clean.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Retention(RetentionPolicy.RUNTIME)
@TestExecutionListeners(value = {IntegrationTestExecutionListener.class,}, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.gugucon.shopping.integration.config;

import io.restassured.RestAssured;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.AbstractTestExecutionListener;

Expand All @@ -17,4 +19,31 @@ public void beforeTestMethod(final TestContext testContext) {

RestAssured.port = serverPort;
}

@Override
public void afterTestMethod(final TestContext testContext) {
final JdbcTemplate jdbcTemplate = getJdbcTemplate(testContext);
truncateTables(jdbcTemplate);
}

private JdbcTemplate getJdbcTemplate(final TestContext testContext) {
return testContext.getApplicationContext().getBean(JdbcTemplate.class);
}

private void truncateTables(final JdbcTemplate jdbcTemplate) {
execute(jdbcTemplate, "SET REFERENTIAL_INTEGRITY FALSE");
getTruncateQueries(jdbcTemplate).forEach(query -> execute(jdbcTemplate, query));
execute(jdbcTemplate, "SET REFERENTIAL_INTEGRITY TRUE");
}

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

private void execute(final JdbcTemplate jdbcTemplate, final String query) {
jdbcTemplate.execute(query);
}
}

0 comments on commit c1e6158

Please sign in to comment.