반응형
단위별 테스트 작성
Test코드를 작성하기 위해서 Test라는 Directory에 Resources라는 폴더를 추가하고,
application-test.yml을 추가해주었다.
<application-test.yml>
spring:
config:
activate:
on-profile: test #'test' 프로파일이 활성화 되었을 때 아래 설정이 적용된다.
datasource:
username: sa
password:
driverClassName: org.h2.Driver # H2 데이터베이스 드라이버 클래스 이름
url: jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL
# DB_CLOSE_DELAY=-1: 메모리 데이터베이스가 애플리케이션 종료 시까지 유지됨
# DATABASE_TO_UPPER=false: 테이블 및 칼럼 이름이 대소문자 구분 없이 사용됨
# MODE=MYSQL: MySQL 모드로 작동하여 MySQL 구문과의 호환성을 제공
jpa:
show-sql: true # 실행된 SQL 쿼리를 출력
generate-ddl: true # JPA가 DDL(Data Definition Language)을 생성하도록 설정
properties:
format-sql: true # SQL 쿼리를 보기 좋게 포맷팅
dialect: org.hibernate.dialect.MySQL8Dialect # MySQL에 맞는 Hibernate 방언 설정
hibernate:
format_sql: true
globally_quoted_identifiers: true # 모든 식별자를 따옴표로 감싸서 처리
ddl-auto: create-drop # 애플리케이션 시작 시 스키마를 생성하고 종료 시 삭제
database-platform: org.hibernate.dialect.MySQL8Dialect # MySQL 방언 설정
database: h2 # H2 데이터베이스 사용
he:
console:
enabled: true # H2 콘솔을 활성화하여 웹 브라우저에서 접근 가능
@DataJpaTest
@ActiveProfiles("test")
@TestPropertySource(locations = "classpath:application-test.yml")
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class UserRepositoryTest {
@Autowired
private UserRepository userRepository;
@Test
void testCreate(){
User user = User.builder()
.userName("Taehwan") // user_name 필드 추가
.userEmail("Taehwan@gmail.com") // user_email 필드 추가
.userPassword("password") // user_password 필드 추가
.build();
User user2 = userRepository.save(user);
Assertions.assertEquals(user2.getUserId(),2L);
Assertions.assertTrue(user.getUserName().equals("Taehwan"));
}
}
• @DataJpaTest: JPA 관련 컴포넌트만 로드하여 테스트를 수행.
• @ActiveProfiles("test"): test 프로파일을 활성화하여 테스트 환경 설정 적용.
• @TestPropertySource(locations = "classpath:application-test.yml"): application-test.yml 파일을 로드하여 테스트 환경 설정 적용.
• @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE): 실제 데이터베이스 설정을 그대로 사용하여 테스트 수행.
이 코드를 통해 테스트를 실행하게 되면,
코드가 실행되고 테스트가 실행되는 것을 확인할 수 있다.
반응형
'Spring > Test' 카테고리의 다른 글
태태개발일지 - Controller계층 Test (0) | 2024.06.09 |
---|---|
태태개발일지 - Service 계층 Test (0) | 2024.06.09 |