자라선

@Autowired ServletContext 주입 테스트 본문

Develop/Test Framework

@Autowired ServletContext 주입 테스트

자라선 2020. 8. 27. 17:15
@Controller
public class AccountEmailCertify {

    @Autowired
    ServletContext servletContext;

    @RequestMapping("/certify")
    public String certify(@RequestParam(required = true) String id,
                          @RequestParam(required = true) String account) throws Exception {
        
        // ServletContext 를 사용함
        final String realPath = servletContext.getRealPath("/xConfig/mail.xml.config");
        
        ....
        return "accountCertify";
    }

}

Controller에서 ServletContext를 사용할때 이것을 테스트 해보려고 한다면 다음과 같다.

 

package net.common.common;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
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.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:config/spring/*.xml"})

// ApplicationContext를 불러와야지 그 하위의 ServletContext를 불러올 수 있음
@WebAppConfiguration
public class AccountEmailCertifyTest {

	//Spy로 Mock형태로 변환하고 Autowired를 사용하여 주입
    @Spy @Autowired
    ServletContext servletContext;

    @InjectMocks
    AccountEmailCertify controller;

    MockMvc mockMvc;

    @Before
    public void setup(){
        MockitoAnnotations.initMocks(this);

        assertThat(controller).isNotNull();
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void certify() throws Exception {
        mockMvc.perform(get("/certify")
                        .param("id", "test")
                        .param("account", "test"))
                .andDo(print());

    }
}

@Autowired를 사용해 주입받은 다음 @Spy를 선언하여 InjectMocks에 Mock으로 할당 받을 수 있도록 설정한다.

 

그러면 @InjectMocks 로 선언된 객체에서 주입이 필요한 오브젝트를

찾아서 선언되어있는 Mock들을 알아서 매핑해 주입한다.

 

 

Comments