Database 선정

  • 일반적으로 테스트 시에는 main 서버에서 사용하는 db를 사용하지 않고 인 메모리 방식의 h2 디비를 사용한다. 
  • 인 메모리 기반이기에 성능이 빠르다.
  • 이 때 실제 db를 사용하고자 한다면 @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)으로 설정하면 된다.

test 설정 파일

  • main 서버와 다른 데이터베이스를 사용해야 하므로 properties에서 설정 변경은 필수적이다.
  • 기본적으로 main 폴더에 있는 application.yml은 로드가 되지만 active profile을 설정하면 다른 yml을 로드할 수 있다.
  • 이 때 profile로 로드된 yml이 기존에 로드된 yml을 덮어씌운다.
jpa를 사용할 시에 repository를 테스트할 필요없다. 하지만 @Query를 이용하거나 QueryDSL을 이용할 때는 테스트를 해야 한다.
org.springframework.transaction.annotation.Transactional의 @Transactional을 붙이면 해당 테스트 메소드가 끝나면 자동으로 Rollback 처리를 해준다.
이 어노테이션이 테스트 메소드 위에 있어야 자동 Rollback 처리를 해준다. 즉, 이 어노테이션이 테스트 메소드에 없고 호출한 메소드에 이 어노테이션이 있는 경우엔 롤백이 되지 않는다.

 

테스트 db 데이터 입력

  • JDBCTemplate를 주입 받아 데이터를 넣을 수 있다. 이를 위해 @BeforeEach를 사용하자. -> properties에 속성값으로 설정해 @Value로 가져오는 방법을 사용하는게 더욱 깔끔하다.
  • @Sql("file.sql")로 테스트별로 적용할 데이터를 설정할 수 있다. @BeforeEach 다음에 @Sql이 실행된다. -> 이 방법을 사용하는게 더 깔끔하고 좋을 거 같다.
@SpringBootTest
@TestPropertySource("/application-test.properties")
public class StudentAndGradeServiceTest {

    @Value("${info.school.name}")
    private String schoolName;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private StudentAndGradeService studentService;

    @Autowired
    private StudentDao studentDao;

    @BeforeEach
    void setUpDatabase() {
        jdbcTemplate.execute("insert into student(id, firstname, lastname, email_address) "
            + "values(1,'Eric','Roby','asdasd@asdasd')");
    }

    @AfterEach
    void setupAfterTransaction() {
        jdbcTemplate.execute("delete from student");
    }

    @Test
    void createStudentService() {
        studentService.createStudent("Choi", "Jaeh", "mail@gmail.com");

        CollegeStudent student = studentDao.findByEmailAddress("mail@gmail.com");

        assertEquals("mail@gmail.com", student.getEmailAddress(), "find by email");
    }

    @Test
    void isStudentNullCheck() {

        assertTrue(studentService.checkIfStudentIsNull(1));

        assertFalse(studentService.checkIfStudentIsNull(0));
    }

    @Test
    void deleteStudentService() {

        Optional<CollegeStudent> deletedCollegeStudent = studentDao.findById(1);

        assertTrue(deletedCollegeStudent.isPresent());

        studentDao.findByEmailAddress(deletedCollegeStudent.get().getEmailAddress());

        studentService.deleteStudent(1);

        deletedCollegeStudent = studentDao.findById(1);

        assertFalse(deletedCollegeStudent.isPresent());
    }

    @Test
    @Sql("/insertData.sql")
    void getGradeBookService() {
        Iterable<CollegeStudent> iterableCollegeStudent = studentService.getGradeBook();

        List<CollegeStudent> collegeStudents = new ArrayList<>();

        System.out.println(schoolName);

        for (CollegeStudent collegeStudent : iterableCollegeStudent) {
            collegeStudents.add(collegeStudent);
        }

        assertEquals(2, collegeStudents.size());
    }
}

'Spring Boot > testing' 카테고리의 다른 글

@WebMvcTest - @EnableJpaAuditing 주의사항  (0) 2024.12.04
RestController 단위 Testing  (0) 2024.11.13
Mock을 통한 Throwing Exception  (0) 2024.11.11
@MockBean & @SpyBean  (0) 2024.11.11
매개변수화된 테스트  (0) 2024.11.11

+ Recent posts