본문 바로가기

개발

WAS 구동 없이 컨트롤러 테스트


테스트 환경

OS : Windows 10 64bit

Spring : 4.1.7.RELEASE

Java : 1.8



1. pom.xml Servlet 변경

<!-- Servlet 주석 처리

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>servlet-api</artifactId>

<version>2.5</version>

<scope>provided</scope>

</dependency> 주석 처리 -->

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>javax.servlet-api</artifactId>

<version>3.1.0</version>

</dependency>



2. 테스트 코드 작성

 - src/test/java/SampleControllerTest


package org.zerock.web;


import javax.inject.Inject;


import org.junit.Before;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import org.springframework.test.context.web.WebAppConfiguration;

import org.springframework.test.web.servlet.MockMvc;

import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import org.springframework.web.context.WebApplicationContext;


@RunWith(SpringJUnit4ClassRunner.class)

@WebAppConfiguration

@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/**/*.xml"})

public class SampleControllerTest {

private static Logger logger = LoggerFactory.getLogger(SampleControllerTest.class);

@Inject

private WebApplicationContext wac;

private MockMvc mockMvc;

@Before

public void setup(){

this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();

logger.info("setup..");

}

@Test

public void testDoA() throws Exception {

mockMvc.perform(MockMvcRequestBuilders.get("/doA"));

}

}


...

...

@Controller

public class SampleController {

private static final Logger logger = LoggerFactory.getLogger(SampleController.class);

@RequestMapping("doA")

public void doA(){

logger.info("doA called ...");

}

}


- MockMvc는 브라우저에서 요청과 응답을 의미하는 객체

- @Before 애노테이션 처리 : 매번 테스트 실행 전에 MockMvc 객체를 생성

- perform() 메소드를 실행하여 GET방식, POST 방식의 호출 사용



* 참조 도서 : 코드로 배우는 스프링 웹 프로젝트


맨 위로