본문 바로가기
Back-end/테스트

Spring Boot MVC 서비스 테스트

by javapp 자바앱 2022. 11. 9.
728x90

 

 

 

전체코드

test/java/com/.../springmvc/StudentAndGradeServiceTest.java

@TestPropertySource("/application.properties")
@SpringBootTest
public class StudentAndGradeServiceTest
{
    @Autowired
    private StudentAndGradeService studentService;

    @Autowired
    private StudentDao studentDao;

    @Autowired
    private MathGradesDao mathGradesDao;

    @Autowired
    private ScienceGradesDao scienceGradesDao;

    @Autowired
    private HistoryGradesDao historyGradesDao;

    @Autowired
    private JdbcTemplate jdbc;

    @Value("${spl.script.create.student}")
    private String sqlAddstudent;
    @Value("${sql.script.create.math.grade}")
    private String sqlAddMathGrade;
    @Value("${spl.script.create.science.grade}")
    private String sqlAddScienceGrade;
    @Value("${spl.script.create.history.grade}")
    private String sqlAddHistoryGrade;
    @Value("${sql.script.delete.stduent}")
    private String sqlDeleteStudent;
    @Value("${sql.script.delete.math.grade}")
    private String sqlDeleteMathGrade;
    @Value("${sql.script.delete.science.grade}")
    private String sqlDeleteScienceGrade;
    @Value("${sql.script.delete.history.grade}")
    private String sqlDeleteHistoryGrade;


    // 테스트 데이터 설정
    @BeforeEach
    public void setupDatabase(){
        jdbc.execute(sqlAddstudent);
        jdbc.execute(sqlAddMathGrade);
        jdbc.execute(sqlAddScienceGrade);
        jdbc.execute(sqlAddHistoryGrade);
    }

//    @Test
//    public void createStudentService(){
//        // TDD
//        studentService.createStudent("java","app","javapp@tistory.com");
//        // 완성하기 위해 코드 작성
//    }

    @Test
    public void createStudentService(){
        // TDD

        // service 로 학생 생성
        studentService.createStudent("java2","app2","javapp2@tistory.com");

        // dao로 email 로 찾기
        CollegeStudent student = studentDao.findByEmailAddress("javapp2@tistory.com");

        assertEquals("javapp2@tistory.com", student.getEmailAddress(), "이메일로 찾기");
    }

    @Test
    public void isStudentNullCheck(){

    }

    @Test void deleteStudentServiceTest(){
        Optional<CollegeStudent> deletedCollegeStudent=studentDao.findById(1);

        assertTrue(deletedCollegeStudent.isPresent()    ,"Return True");

        studentService.deleteStudent(1);
        deletedCollegeStudent = studentDao.findById(1);
        Optional<MathGrade> deletedMathGrade = mathGradesDao.findById(1);

        assertFalse(deletedCollegeStudent.isPresent(),"Return False");
        assertFalse(deletedMathGrade.isPresent());
    }


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

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

        for(CollegeStudent collegeStudent : iterableCollegeStudents){
            collegeStudentList.add(collegeStudent);
        }

        assertEquals(5, collegeStudentList.size());
    }

    @DisplayName("학생 성적 생성")
    @Test
    public void createGradeService(){
        // create the grade
        assertTrue(studentService.createGrade(80.50,1,"math"));
        assertTrue(studentService.createGrade(80.50,1,"science"));
        assertTrue(studentService.createGrade(80.50,1,"history"));

        // get all grades with studentId
        Iterable<MathGrade> mathGrades = mathGradesDao.findGradeByStudentId(1);
        Iterable<ScienceGrade> scienceGrades = scienceGradesDao.findGradeByStudentId(1);
        Iterable<HistoryGrade> historyGrades = historyGradesDao.findGradeByStudentId(1);

        // verify there is grades
        assertTrue(((Collection<MathGrade>)mathGrades).size() == 2, "Student has math grades");
        assertTrue(((Collection<ScienceGrade>)scienceGrades).size() == 2, "Student has 과학 성적");
        assertTrue(((Collection<HistoryGrade>)historyGrades).size() == 2, "역사 성적 가지고 있음");
    }

    @DisplayName("성적 생성 실패하는 경우")
    @Test
    public void createGradeServiceReturnFalse(){
        assertFalse(studentService.createGrade(105,1,"math")); // grade 초과
        assertFalse(studentService.createGrade(-5,1,"math")); // 마이너스
        assertFalse(studentService.createGrade(80.50, 2, "math")); // 없는 id
        assertFalse(studentService.createGrade(80.50,1,"invalid subject"));
    }

    @DisplayName("성적 삭제")
    @Test
    public void deleteGradeService(){
        assertEquals(1,studentService.deleteGrade(1,"math"), "Returns student Id after delete");
    }

    @Test
    public void  deleteGradeServiceReturnsStudentIdOfZero(){
        assertEquals(-1, studentService.deleteGrade(0,"science"),
                "grade id 가 0을 가지고 있는 학생이 없다.");
        assertEquals(-1, studentService.deleteGrade(1,"no way"), "해당 과목 없음");
    }

    @DisplayName("GradebookCollegeStudent 정보 가져오기")
    @Test
    public void studentInformation(){
        GradebookCollegeStudent gradebookCollegeStudent = studentService.studentInformation(1);

        assertNotNull(gradebookCollegeStudent);
        assertEquals(1, gradebookCollegeStudent.getId());
        assertEquals("java",gradebookCollegeStudent.getFirstname());
    }

    @DisplayName("학생이 존재 하지 않음")
    @Test
    public void studentINformationServiceResturnNull(){
        GradebookCollegeStudent gradebookCollegeStudent = studentService.studentInformation(0);

        assertNull(gradebookCollegeStudent);
    }


    @AfterEach
    public void setupAfterTransaction(){
        jdbc.execute(sqlDeleteStudent);
        jdbc.execute(sqlDeleteMathGrade);
        jdbc.execute(sqlDeleteScienceGrade);
        jdbc.execute(sqlDeleteHistoryGrade);
    }
}

 

 


 

서비스

com/../springmvc/service/StudentAndGradeService

@Service
@Transactional
public class StudentAndGradeService {
    private StudentDao studentDao;

    @Autowired
    @Qualifier("mathGrades")
    private MathGrade mathGrade;

    @Autowired
    private MathGradesDao mathGradesDao;

    @Autowired
    @Qualifier("scienceGrades")
    private ScienceGrade scienceGrade;

    @Autowired
    private ScienceGradesDao scienceGradesDao;

    @Autowired
    @Qualifier("historyGrades")
    private HistoryGrade historyGrade;

    @Autowired
    private HistoryGradesDao historyGradesDao;

    @Autowired
    private StudentGrades studentGrades;

    public StudentAndGradeService(StudentDao studentDao) {
        this.studentDao = studentDao;
    }

    public void createStudent(String firstname, String lastname, String email) {
        CollegeStudent collegeStudent = new CollegeStudent(firstname, lastname, email);
        studentDao.save(collegeStudent);
    }

    public void deleteStudent(int id) {
        if (checkIfStudentIsNull(id)) {
            studentDao.deleteById(id);
            mathGradesDao.deleteByStudentId(id);
            scienceGradesDao.deleteByStudentId(id);
            historyGradesDao.deleteByStudentId(id);
        }
    }

    public boolean checkIfStudentIsNull(int id) {
        return studentDao.existsById(id);
    }

    public Iterable<CollegeStudent> getGradebook() {
        return studentDao.findAll();
    }

    public boolean createGrade(double grade, int studentId, String gradeType) {
        if (!checkIfStudentIsNull(studentId)) {
            return false;
        }
        if (grade >= 0 && grade <= 100) {
            if (gradeType.equals("math")) {
                mathGrade.setId(0);
                mathGrade.setGrade(grade);
                mathGrade.setStudentId(studentId);
                mathGradesDao.save(mathGrade);
                return true;
            }
            if (gradeType.equals("science")) {
                scienceGrade.setId(0);
                scienceGrade.setGrade(grade);
                scienceGrade.setStudentId(studentId);
                scienceGradesDao.save(scienceGrade);
                return true;
            }
            if (gradeType.equals("history")) {
                historyGrade.setId(0);
                historyGrade.setGrade(grade);
                historyGrade.setStudentId(studentId);
                historyGradesDao.save(historyGrade);
                return true;
            }
        }
        return false;
    }

    public int deleteGrade(int id, String gradeType) {
        int studentId = -1;
        if (gradeType.equals("math")) {
            Optional<MathGrade> grade = mathGradesDao.findById(id);
            if (!grade.isPresent()) {
                return studentId;
            }
            studentId = grade.get().getStudentId();
            mathGradesDao.deleteById(id);
        }
        if (gradeType.equals("science")) {
            Optional<ScienceGrade> grade = scienceGradesDao.findById(id);
            if (!grade.isPresent()) {
                return studentId;
            }
            studentId = grade.get().getStudentId();
            scienceGradesDao.deleteById(id);
        }
        if (gradeType.equals("history")) {
            Optional<HistoryGrade> grade = historyGradesDao.findById(id);
            if (!grade.isPresent()) {
                return studentId;
            }
            studentId = grade.get().getStudentId();
            historyGradesDao.deleteById(id);
        }
        return studentId;
    }

    public GradebookCollegeStudent studentInformation(int id) {
        if(!checkIfStudentIsNull(id)){
            return null;
        }

        Optional<CollegeStudent> student = studentDao.findById(id);
        Iterable<MathGrade> mathGrades = mathGradesDao.findGradeByStudentId(id);
        Iterable<ScienceGrade> scienceGrades= scienceGradesDao.findGradeByStudentId(id);
        Iterable<HistoryGrade> historyGrades = historyGradesDao.findGradeByStudentId(id);

        List<Grade> mathGradeList = new ArrayList<>();
        mathGrades.forEach(mathGradeList::add);

        List<Grade> scienceGradeList = new ArrayList<>();
        scienceGrades.forEach(scienceGradeList::add);

        List<Grade> historyGradeList = new ArrayList<>();
        historyGrades.forEach((h)->historyGradeList.add(h));

        studentGrades.setMathGradeResults(mathGradeList);
        studentGrades.setScienceGradeResults(scienceGradeList);
        studentGrades.setHistoryGradeResults(historyGradeList);

        GradebookCollegeStudent gradebookCollegeStudent = new GradebookCollegeStudent(student.get().getId(),
                student.get().getFirstname(), student.get().getLastname(), student.get().getEmailAddress(),studentGrades);
        return gradebookCollegeStudent;
    }
}

 

 

 


 

 

메인 함수

@SpringBootApplication
public class MvcTestingExampleApplication {

	public static void main(String[] args) {
		SpringApplication.run(MvcTestingExampleApplication.class, args);
	}

	@Bean
	@Scope(value = "prototype")
	CollegeStudent getCollegeStudent() {
		return new CollegeStudent();
	}

	@Bean
	@Scope(value = "prototype")
	Grade getMathGrade(double grade) {
		return new MathGrade(grade);
	}

	@Bean
	@Scope(value = "prototype")
	@Qualifier("mathGrades")
	MathGrade getGrade() {
		return new MathGrade();
	}

	@Bean
	@Scope(value = "prototype")
	@Qualifier("scienceGrades")
	ScienceGrade getScienceGrade() {
		return new ScienceGrade();
	}

	@Bean
	@Scope(value = "prototype")
	@Qualifier("historyGrades")
	HistoryGrade getHistoryGrade() {
		return new HistoryGrade();
	}

}

 

댓글