: spring-test 모듈을 이용해 스프링을 간단하게 가동한다. (Junit 4.0이상)
기본
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= {RootConfig.class})
@Log4j
public class 테스트클래스명 {
@Setter(onMethod_ = @Autowired) //생성자 주입
private 필드타입 필드명;
@Test //JUnit에서 테스트 대상 표시
public void 테스트메소드명() {
...
}
}
Controller
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { RootConfig.class, ServletConfig.class })
@Log4j
public class 테스트클래스명 {
@Setter(onMethod_ = @Autowired) //생성자 주입
private WebApplicationContext ctx;
private MockMvc mockMvc;
@Before //테스트 전에 항상 실행되는 메소드
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build(); //초기화
}
@Test
public void testList() throws Exception {
log.info(mockMvc.perform(MockMvcRequestBuilders.호출방식("호출할 URL"))
.andReturn()
.getModelAndView()
.getModelMap()); //.getViewName());
}
}
테스트 관련 어노테이션
- @Runwith(SpringJUnit4ClassRunner.class)
: 테스트 시 필요한 클래스(SpringJUnit4 ClassRunner)를 지정한다.
: 해당 테스트 코드가 스프링 실행 역할 한다는 것을 뜻한다.
- @ContextConfiguration
: 스프링이 실행될 때 어떤 설정정보을 읽을지 명시한다. 자동생성된 RootConfig.java(root-context.xml)와 ServletConfig.java(servlet-context.xml)의 경로를 지정한다.
지정된 클래스나 문자열을 이용해 필요한 객체를 스프링의 Bean으로 등록한다.
ex)
//XML 설정
@ContextConfiguration(classes= {RootConfig.class})
//JAVA 설정
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
- @Log4j
: Lombok을 이용해서 로그를 기록하는 Logger를 변수로 생성한다.
- @Test
: 단위 테스트 대상을 표시한다.
Tomcat(WAS)을 실행하지 않는 테스트 - Controller
- @WebAppConfiguration
: 빈을 등록한다. ServletContext - WebApplicationContext를 이용하기 위해 사용한다.
- @Before (import org.junit.Before)
: 테스트 전에 항상 실행되는 메서드이다.
- MockMvc
: springMVC 테스트를 도와주는 가짜 URL과 파라미터 등을 만든다.
- MockMvcRequestBuilders
: 설정한 호출방식으로 request 요청을 한다.
+ 실행 결과 확인
: Run As - > Junit Test
실전
mapper테스트
VO.java
@Data
public class BoardsVO {
private int boardno;
private String boardtitle;
private String boardcontent;
private String boardwriter;
private int boarddelet;
private int boardtype;
private Date registerdate;
private Date updatedate;
}
mapperInterface.java
public interface BoardsMapper {
@Select("select * from boards where boardno>0")
public List<BoardsVO> getList();
}
mapperTests.java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { RootConfig.class })
@Log4j
public class BoardsMapperTests {
@Setter(onMethod_ = @Autowired)
private BoardsMapper mapper;
@Test
public void testGetList() {
//람다식 반복처리
mapper.getList().forEach(B -> log.info(B));
//향상된 for문
// List<BoardsVO> list = (ArrayList<BoardsVO>) mapper.getList();
// for (BoardsVO board : list) {
// System.out.println(board);
// }
//for문
// List<BoardsVO> list = (ArrayList<BoardsVO>) mapper.getList();
// for(int i = 0; i>list.size(); i++) {
// log.info(list.get(i));
// }
}
}
결과
'SPRING' 카테고리의 다른 글
SPRING mybatis <selectKey> (0) | 2023.02.13 |
---|---|
SPRING 의존성 주입 (0) | 2023.02.08 |
SPRING 설정 (JAVA Configuration) (0) | 2023.02.06 |
SPRING 설정 (XML) (0) | 2023.02.04 |
SPRING 파일 업로드 다운로드 (0) | 2023.01.17 |