728x90
Maven 종속성 추가
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
JUnit 5가 포함되어있어서 자유롭게 사용할 수 있습니다.
test 패키지 추가
main 의 패키지와 test 의 패키지 경로가 다르다면
test 클래스에서 @SpringBootTest 애노테이션의 classes 파라미터를 통해
메인의 부트 실행 클래스를 명시
@SpringBootTest(classes = MvcTestingExampleApplication.class)
application.properties 파일 읽기
@SpringBootTest(classes = MvcTestingExampleApplication.class)
public class ApplicationExampleTest {
private static int count =0;
@Value("${info.app.name}")
private String appInfo;
@Value("${info.app.description}")
private String appDescription;
@Value("${info.school.name}")
private String schoolName;
@Value("${info.app.version}")
private String appVersion;
...
application.properties
info.school.name=luv2code
info.app.name=My Super Cool Gradebook
info.app.description=a fun way to track student grades!
info.app.version=1.0.0
테스트 코드에 Spring Beans 주입
Interface Student
public interface Student {
String studentInformation();
String getFullName();
}
@Component 를 통해 빈 등록
@Component
public class StudentGrades {
더보기
@Component
public class StudentGrades {
List<Double> mathGradeResults;
/*
* CAN HAVE MULTIPLE DIFFERENT TYPES OF GRADES
* FOR 2.x WE WILL ONLY HAVE A MATH GRADE
* */
public StudentGrades() {
}
public StudentGrades(List<Double> mathGradeResults) {
this.mathGradeResults = mathGradeResults;
/*
Add other subject grades here in future lessons
*/
}
/*
Add other subject grades here in future lessons
*/
public double addGradeResultsForSingleClass(List<Double> grades) {
double result = 0;
for (double i : grades) {
result += i;
}
return result;
}
public double findGradePointAverage (List<Double> grades ) {
int lengthOfGrades = grades.size();
double sum = addGradeResultsForSingleClass(grades);
double result = sum / lengthOfGrades;
// add a round function
BigDecimal resultRound = BigDecimal.valueOf(result);
resultRound = resultRound.setScale(2, RoundingMode.HALF_UP);
return resultRound.doubleValue();
}
public Boolean isGradeGreater(double gradeOne, double gradeTwo) {
if (gradeOne > gradeTwo) {
return true;
}
return false;
}
public Object checkNull(Object obj) {
if ( obj != null ) {
return obj;
}
return null;
}
public List<Double> getMathGradeResults() {
return mathGradeResults;
}
public void setMathGradeResults(List<Double> mathGradeResults) {
this.mathGradeResults = mathGradeResults;
}
@Override
public String toString() {
return "StudentGrades{" +
"mathGradeResults=" + mathGradeResults +
'}';
}
}
CollegeStudent
더보기
public class CollegeStudent implements Student {
private String firstname;
private String lastname;
private String emailAddress;
private StudentGrades studentGrades;
public CollegeStudent() {
}
public CollegeStudent(String firstname, String lastname, String emailAddress) {
this.firstname = firstname;
this.lastname = lastname;
this.emailAddress = emailAddress;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public StudentGrades getStudentGrades() {
return studentGrades;
}
public void setStudentGrades(StudentGrades studentGrades) {
this.studentGrades = studentGrades;
}
@Override
public String toString() {
return "CollegeStudent{" +
"firstname='" + firstname + '\'' +
", lastname='" + lastname + '\'' +
", emailAddress='" + emailAddress + '\'' +
", studentGrades=" + studentGrades +
'}';
}
@Override
public String studentInformation() {
return getFullName() + " " + getEmailAddress();
}
@Override
public String getFullName() {
return getFirstname() + " " + getLastname();
}
}
메인 클래스
@SpringBootApplication
public class MvcTestingExampleApplication {
public static void main(String[] args) {
SpringApplication.run(MvcTestingExampleApplication.class, args);
}
@Bean(name = "collegeStudent")
@Scope(value = "prototype")
CollegeStudent getCollegeStudent() {
return new CollegeStudent();
}
}
@Scope(value = "prototype") : 싱글톤이 아니라 인스턴스를 새로 생성할 수 있게 함.
최종 ApplicationExampleTest.java
(test 패키지)
@SpringBootTest(classes = MvcTestingExampleApplication.class)
public class ApplicationExampleTest {
private static int count =0;
@Value("${info.app.name}")
private String appInfo;
@Value("${info.app.description}")
private String appDescription;
@Value("${info.school.name}")
private String schoolName;
@Value("${info.app.version}")
private String appVersion;
@Autowired
CollegeStudent student;
@Autowired
StudentGrades studentGrades;
@BeforeEach
public void beforeEach(){
count++;
System.out.println("Testing: "+appInfo + " which is "
+ appDescription+ " , Version : "+appVersion+", Execution of test method " +count);;
student.setFirstname("jav");
student.setLastname("app");
student.setEmailAddress("javapp@tistory.com");
studentGrades.setMathGradeResults(new ArrayList<>(Arrays.asList(100.0, 85.5, 76.5,91.75)));
student.setStudentGrades(studentGrades);
}
@Test
void basicTest(){}
}
@Autowired 를 통해 빈 주입
프로토타입 Beans
CollegeStudent studentTwo = context.getBean("collegeStudent", CollegeStudent.class);
>> 메인 클래스에서 "collegeStudent" 이름으로 @Bean 을 통해 객체를 IoC에 등록
@SpringBootTest(classes = MvcTestingExampleApplication.class)
public class ApplicationExampleTest {
...
@Autowired
ApplicationContext context;
@DisplayName("grade 값 없이 학생 생성")
@Test
public void createStudentWithOutGradesInit()
{
CollegeStudent studentTwo = context.getBean("collegeStudent", CollegeStudent.class);
studentTwo.setFirstname("java");
studentTwo.setLastname("pp");
studentTwo.setEmailAddress("javapp@tistory.com");
assertNotNull(studentTwo.getFirstname());
assertNotNull(studentTwo.getLastname());
assertNotNull(studentTwo.getEmailAddress());
assertNull(studentGrades.checkNull(studentTwo.getStudentGrades()));
}
@DisplayName("학생 인스턴스 프로토타입 검증")
@Test
public void verifyStudentsArePrototypes(){
CollegeStudent studentTwo = context.getBean("collegeStudent",CollegeStudent.class);
assertNotSame(student, studentTwo);
}
@DisplayName("성적의 결과와 평균 찾기")
@Test
public void findGradePointAverage()
{
assertAll("람다식으로 여러 개의 테스트 실행",
()-> assertEquals(300, studentGrades.addGradeResultsForSingleClass(
student.getStudentGrades().getMathGradeResults())),
()-> assertEquals(89,studentGrades.findGradePointAverage(
student.getStudentGrades().getMathGradeResults()
))
);
}
}
'Back-end > 테스트' 카테고리의 다른 글
Spring Boot MVC 데이터베이스 통합 테스트 @Sql (0) | 2022.10.29 |
---|---|
Spring Boot Unit Testing - Mocking with Mockito - @MockBean, ReflectionTestUtils (0) | 2022.10.21 |
TDD 테스트 주도 개발 연습 (0) | 2022.10.05 |
JUnit - 코드 커버리지 테스트 (0) | 2022.09.25 |
JUnit 테스트 - Assertions (0) | 2022.09.24 |
댓글