<!-- Test : 테스트 프로그램 작성 및 실행에 필요한 라이브러리 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<!-- <scope>test</scope> -->
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<!-- => SpringTest 기능을 제공하기 위한 라이브러리 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework-version}</version>
<!-- <scope>test</scope> -->
</dependency>
테스트 프로그램에서 사용할 로그 구현체의 환경설정파일 변경
=> [src/test/resources] 패키지 폴더의 [log4j.xml] 파일의 내용 변경
[src/test/java] 패키지 폴더에 테스트 클래스(테스트 프로그램) 작성
=> junit 라이브러리와 spring-test 라이브러리의 scope 속성을 주석 처리한 후 클래스 작성
테스트 프로그램 실행
테스트 프로그램을 실행하기 위한 클래스를 설정하는 어노테이션
테스트 클래스를 객체로 생성하여 테스트 메소드를 호출해 테스트 명령 실행
value 속성: 테스트 프로그램을 실행하기 위한 클래스의 Class 객체를 속성값으로 설정
=> value 속성외에 다른 속성이 없는 경우 속성값만 설정 가능
SpringJUnit4ClassRunner 클래스는 스프링 컨테이너(ApplicationContext 객체)를 생성하여 테스트
클래스에게 객체 제공
스프링 컨테이너에게 Spring Bean Configuration File을 제공하는 어노테이션
locations 속성: Spring Bean Configuration File 경로를 속성값으로 설정
테스트 메소드로 설정하기 위한 어노테이션
SpringJUnit4ClassRunner 클래스에 의해 테스트 클래스가 객체로 생성된 후 자동 호출되는 메소드
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/root-context.xml"})
@Slf4j
public class DataSourceTest {
//테스트 클래스의 메소드에서 사용될 객체를 저장하기 위한 필드 작성
// => @Autowired 어노테이션을 사용하여 필드에 객체가 저장된 의존성 주입
// => 필드 레벨의 의존성 주입 가능 - 생성자 레벨의 의존성 주입 불가능
@Autowired
private DataSource dataSource;
//@Test : 테스트 메소드로 설정하기 위한 어노테이션
// => SpringJUnit4ClassRunner 클래스에 의해 테스트 클래스가 객체로 생성된 후 자동 호출되는 메소드
@Test
public void testDataSource() throws SQLException {
log.info("DataSource = "+dataSource);
Connection connection=dataSource.getConnection();
log.info("Connection = "+connection);
connection.close();
}
테스트 메소드의 호출 순서를 설정하기 위한 어노테이션
value 속성: MethodSorters Enum 자료형의 상수필드를 속성값으로 설정
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/root-context.xml"
, "file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml"})
@FixMethodOrder(value = MethodSorters.NAME_ASCENDING)
@Slf4j
public class StudentServiceTest {
@Autowired
private StudentService studentService;
@Test
public void testAddStudent() {
Student student=Student.builder().no(7000).name("고길동").phone("010-5412-2134")
.address("서울시 광진구").birthday("1998-07-27").build();
studentService.addStudent(student);
}
@Test
public void testGetStudentList() {
List<Student> studentList=studentService.getStudentList();
for(Student student : studentList) {
log.info(student.toString());
}
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
//[*] 기호를 사용해 Spring Bean Configuration File 제공 가능
// => [**] 기호를 사용하면 하위 폴더의 작성된 Spring Bean Configuration File 제공
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/**/*.xml"})
@Slf4j
public class StudentControllerTest {
//WebApplicationContext 객체(스프링 컨테이너)를 제공받아 필드에 저장되도록 의존성 주입
@Autowired
private WebApplicationContext context;
//MockMvc 객체를 저장하기 위한 필드
// => MockMvc 객체 : 요청과 응답을 가상으로 제공하기 위한 객체 - Front Controller 기능 제공
// 가짜 MVC
private MockMvc mvc;
//@Before : 테스트 메소드 호출 전에 실행될 명령이 작성된 메소드에 사용하는 어노테이션
// => 초기화 처리하는 기능을 제공하는 메소드
@Before
public void setup() {
// MockMvc 객체를 생성하여 필드에 저장
//MockMvcBuilders.webAppContextSetup(WebApplicationContext context)
// => MockMvcBuilder 객체를 생성하여 반환하는 메소드
// => Front Controller 기능을 제공하는 MockMvc 객체에 스프링 컨테이너를 제공하기 위해
//매개변수에 WebApplicationContext 객체 전달
//MockMvcBuilder.build() : MockMvc 객체를 반환하는 메소드
mvc=MockMvcBuilders.webAppContextSetup(context).build();
log.info("MockMvc 객체 생성");
}
@Test
public void testStudentDisplay() throws Exception {
//MockMvcRequestBuilders.get(String url) : 요청 URL 주소의 페이지를 GET 방식으로
//요청하기 위한 RequestBuilder 객체를 반환하는 정적메소드
//MockMvc.perform(RequestBuilder requestBuilder) : RequestBuilder 객체에 저장된 정보를
//사용해 페이지를 요청하는 메소드 - MockMvc 요청 처리 메소드 호출
// => 요청 처리 메소드의 실행결과가 저장된 ResultActions 객체 반환
//ResultActions.andReturn() : 요청 처리 메소드의 반환값(ModelAndView 객체)이 저장된 MvcResult 객체를 반환하는 메소드
MvcResult result=mvc.perform(MockMvcRequestBuilders.get("/student/display")).andReturn();
log.info(result.getModelAndView().getViewName());
log.info(result.getModelAndView().getModel().toString());
}
}