CardService
ํด๋์ค์ ๋ํ ํ
์คํธ ์ฝ๋๋ฅผ ์ง๋๋ฐ, ์๋ ์์กดํ๊ณ ์๋ ํด๋์ค๊ฐ ๋ง์ Mockito
๋ฅผ ํ์ฉํ๊ธฐ๊ฐ ๋๋ฌด ์ด๋ ค์๋ค...
given-willReturn ์ด ๋๋ฌด ๋ง์ด ์ฌ์ฉ๋๊ณ , ์์ ์ํฐํฐ์ id๋ฅผ ์ฐธ์กฐํ๋ ๊ฒฝ์ฐ๊ฐ ๋ง๊ธฐ ๋๋ฌธ์,
์ฐจ๋ผ๋ฆฌ H2๋ฅผ ์ด์ฉํ์ฌ ์ค์ ๊ฐ์ ๋ฃ๋๋ก ์งํํ๋ค.
๊ฐ๋ค์ ์ ์ฅํ๋ ๊ฒ์ ๋ฌธ์ ๊ฐ Never ์์๋ค. ํ์ง๋ง!! โ ๏ธ ํ ๊ฐ์ ํ
์คํธ๊ฐ ๋๋ ๋๋ง๋ค ๋ฐ์ดํฐ ๊ฐ๋ค์ ๋ชจ๋ ์ง์์ค์ผ ํ๋๋ฐ ๋ค๋ฅธ ์ํฐํฐ์ repository๋ฅผ ์ง์ ์ฌ์ฉํ๋ ๊ฒ์ด ์๋๋ผ, service ๋จ์ ๊ฑฐ์ณ์ ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์ deleteAll
๋ฉ์๋๋ฅผ ์ฌ์ฉํ ์ ์์๋ค.
๊ทธ๋์ ๋ค์ mockito ๋ฅผ ์ ์ฉํด๋ณด๋ คํ๋ค ์ฅ๋ ฌํ ์คํจ.......
๋ค์ ๊ธฐ์กด์ผ๋ก ๋์์์ ์ฌ๋ฌ ์์น๋ฅผ ํด๋ณธ ๊ฒฐ๊ณผ Database๋ฅผ ์ง์์ฃผ๋ ํด๋์ค๋ฅผ ๋ง๋ค๋ฉด ๋์๋ค.
์ด๊ธฐ์ ๋ค๋ฅธ ๋ถ๋ค์ ์ฝ๋๋ฅผ ์ฐธ์กฐํ ๊ฒฐ๊ณผ๋ ๋ฐ์ ์ฝ๋
@Component
@Profile("test")
public class DatabaseCleaner implements InitializingBean {
@PersistenceContext
private EntityManager entityManager;
private List<String> tableNames;
@Override
public void afterPropertiesSet() {
tableNames = entityManager.getMetamodel().getEntities().stream()
.filter(e -> e.getJavaType().getAnnotation(Entity.class) != null)
.map(e -> CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, e.getName()))
.collect(Collectors.toList());
}
@Transactional
public void execute() {
entityManager.flush();
entityManager.createNativeQuery("SET REFERENTIAL_INTEGRITY FALSE").executeUpdate();
for (String tableName : tableNames) {
System.out.println(tableName);
entityManager.createNativeQuery("TRUNCATE TABLE " + tableName).executeUpdate();
entityManager.createNativeQuery("ALTER TABLE " + tableName + " ALTER COLUMN ID RESTART WITH 1").executeUpdate();
}
entityManager.createNativeQuery("SET REFERENTIAL_INTEGRITY TRUE").executeUpdate();
}
๊ทธ๋ฐ๋ฐ ์ฌ๊ธฐ์ ๋ฌธ์ ๋ tableNames๋ฅผ ๊ฐ์ ธ์ฌ ๋, DB ๋ด์ ์ด๋ฆ์ด ์๋๋ผ, Entity Class ์์ฒด์ ์ด๋ฆ์ ๊ฐ์ ธ์ค๋ ๋ฌธ์ ๊ฐ ๋ฐ์ํ๋ค.
๊ทธ๋์ ์์ ๋ ์ฝ๋
@Component
@Profile("test")
public class DatabaseCleaner implements InitializingBean {
@PersistenceContext
private EntityManager entityManager;
private List<String> tableNames = List.of("comment", "checklists", "cards", "card_worker", "columns", "boards", "board_worker", "users");
@Override
public void afterPropertiesSet() {
}
@Transactional
public void execute() {
entityManager.flush();
entityManager.createNativeQuery("SET REFERENTIAL_INTEGRITY FALSE").executeUpdate();
for (String tableName : tableNames) {
System.out.println(tableName);
entityManager.createNativeQuery("TRUNCATE TABLE " + tableName).executeUpdate();
entityManager.createNativeQuery("ALTER TABLE " + tableName + " ALTER COLUMN ID RESTART WITH 1").executeUpdate();
}
entityManager.createNativeQuery("SET REFERENTIAL_INTEGRITY TRUE").executeUpdate();
}
}
๊ทธ๋ฅ ๋ฃ์ด์คฌ๋ค ใ
......;;;
์ ๋์ํ๋ฉด ๋๋ค!~!ใ
'TIL๐ฅ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
24.01.04 TIL (1) | 2024.01.05 |
---|---|
24.01.03 TIL (0) | 2024.01.03 |
23.12.28 TIL (0) | 2023.12.28 |
23.12.27 TIL (0) | 2023.12.27 |
23.12.26 TIL (0) | 2023.12.26 |