인프런의 "더 자바, 애플리케이션을 테스트하는 다양한 방법”을 보고 정리한 것임
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.projectlombok:lombok:1.18.20'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.postgresql:postgresql:42.3.1'
/* testcontainers */
testImplementation 'org.testcontainers:postgresql:1.16.2'
testImplementation 'org.testcontainers:junit-jupiter'
}
dependencyManagement {
imports {
mavenBom("org.testcontainers:testcontainers-bom:1.16.2")
}
}
spring.datasource.url=jdbc:tc:postgresql:///postgres
// Spring Boot version 2.3.0 이면 추가 해야함
// spring.datasource.driver-class-name=org.testcontainers.jdbc.ContainerDatabaseDriver
spring.jpa.hibernate.ddl-auto=create-drop
@SpringBootTest
@ExtendWith(MockitoExtension.class)
@ActiveProfiles("test")
@Testcontainers
class TestcontainersTest {
@Mock
MemberService memberService;
@Autowired
StudyRepository studyRepository;
@Container
static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres").withDatabaseName("study-db");
@BeforeAll
static void beforeAll() {
String jdbcUrl = postgreSQLContainer.getJdbcUrl();
String databaseName = postgreSQLContainer.getDatabaseName();
System.out.println("databaseName : " + databaseName + " / jdbcUrl : " + jdbcUrl);
}
@BeforeEach
void beforeEach() {
studyRepository.deleteAll();
}
@Test
void createNewStudy() {
StudyService studyService = new StudyService(memberService, studyRepository);
assertNotNull(studyService);
Member member = new Member();
member.setId(1L);
member.setEmail("lee@gamil.com");
Study study = new Study(10, "테스트");
when(memberService.findById(1L)).thenReturn(Optional.of(member));
studyService.createNewStudy(1L, study);
assertNotNull(study.getOwnerId());
assertEquals(member.getId(), study.getOwnerId());
verify(memberService, times(1)).notify(study);
verifyNoMoreInteractions(memberService);
}
@DisplayName("다른 사용자가 볼 수 있도록 스터디를 공개한다.")
@Test
void openStudy() {
// Given
StudyService studyService = new StudyService(memberService, studyRepository);
Study study = new Study(10, "the Java, Test");
// given(studyRepository.save(study)).willReturn(study);
// When
studyService.openStudy(study);
// Then
assertEquals(study.getStatus(),StudyStatus.OPENED);
assertNotNull(study.getOpenedDateTime());
then(memberService).should().notify(study);
}
}
New GenericContainer(String imageName)
withEnv(key, value)
withCommand(String cmd...)