Spring Controllerユニットテスト

11623 ワード

通常の方法はWEBサーバのテストを起動しエラーが発生しました.WEBコードを変更してWEBテストを再開します. 
大量の時間はWEBサーバの起動に無駄にしています.
今日はWEBを起動せずにユニットテストを採用する方法を紹介します. 
この方法はSprigMVCとSpring Testフレームに基づいている.
package com.spring;  
  
import java.io.FileNotFoundException;  
import java.io.IOException;  
import java.util.ArrayList;  
import java.util.List;  
import java.util.Map;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import org.json.JSONObject;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.http.MediaType;  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.bind.annotation.ResponseBody;  
import org.springframework.web.context.ContextLoader;  
import org.springframework.web.context.WebApplicationContext;  
import org.springframework.web.context.support.WebApplicationContextUtils;  
import org.springframework.web.servlet.ModelAndView;  
  
@Controller  
@RequestMapping(value = "/spring")  
public class Action {  
  
    @Autowired  
    Teacher teacher;  
    // spring   restful     
      
    @ResponseBody  
    @RequestMapping(value = "/rest/{ownerId}.do", method = RequestMethod.GET)  
    public String findOwner(@PathVariable String ownerId, Model model,  
            HttpServletResponse rep) throws IOException {  
        return ownerId;  
    }  
  
    @RequestMapping(value = "/test.do", method = RequestMethod.GET)  
    public String testa(Model model, HttpServletResponse rep)  
            throws IOException {  
        model.addAttribute("abc", "efd");  
        model.addAttribute(teacher);  
        return "a";  
    }  
  
    @ResponseBody  
    //      @ResponseBody       teacher     3.2                   
    @RequestMapping(value = "/testb.do", method = RequestMethod.GET)  
    public String testb(Model model, HttpServletResponse rep,  
            HttpServletRequest req, String ex) throws IOException {  
        // WEB   SPRING    
        WebApplicationContext wac = WebApplicationContextUtils  
                .getRequiredWebApplicationContext(req.getServletContext());  
        return new JSONObject(wac.getBean(Teacher.class)).toString();  
    }  
  
    @ResponseBody  
    @RequestMapping(value = "/post.do", method = RequestMethod.POST)  
    public String post(Model model, HttpServletResponse rep,  
            HttpServletRequest req, String ex) throws IOException {  
        return new JSONObject(req.getParameterMap()).toString();  
    }  
  
}
  
再ユニットテストコード
import java.awt.print.Printable;  
import java.io.IOException;  
  
import javax.servlet.http.HttpServletResponse;  
  
import org.junit.Before;  
import org.junit.Test;  
import org.junit.runner.RunWith;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.http.MediaType;  
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.ResultHandler;  
import org.springframework.test.web.servlet.ResultMatcher;  
import org.springframework.ui.Model;  
import org.springframework.test.context.transaction.TransactionConfiguration;  
import org.springframework.transaction.annotation.Transactional;  
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;  
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;  
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;  
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.context.WebApplicationContext;  
  
@RunWith(SpringJUnit4ClassRunner.class)  
@WebAppConfiguration  
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })  
//                                     
@TransactionConfiguration(defaultRollback = true)  
//    XML        ~~~           
@Transactional  
public class ExampleTests {  
  
    @Autowired  
    private WebApplicationContext wac;  
  
    private MockMvc mockMvc;  
  
    @Before  
    public void setup() {  
        // webAppContextSetup      static import  
        // webAppContextSetup    WEB      fileter       listenCLASS  
        // WebApplicationContext context =  
        // ContextLoader.getCurrentWebApplicationContext();  
        //                     
        this.mockMvc = webAppContextSetup(this.wac).build();  
    }  
  
    @Test  
        //              
        @Rollback(false)  
    public void ownerId() throws Exception {  
        mockMvc.perform((get("/spring/rest/4.do"))).andExpect(status().isOk())  
                .andDo(print());  
    }  
  
    @Test  
    public void test() throws Exception {  
        mockMvc.perform((get("/spring/test.do"))).andExpect(status().isOk())  
                .andDo(print())  
                .andExpect(model().attributeHasNoErrors("teacher"));  
    }  
  
    @Test  
    public void testb() throws Exception {  
        mockMvc.perform((get("/spring/testb.do"))).andExpect(status().isOk())  
                .andDo(print());  
    }  
  
    @Test  
    public void getAccount() throws Exception {  
        mockMvc.perform((post("/spring/post.do").param("abc", "def")))  
                .andExpect(status().isOk()).andDo(print());  
    }  
  
}
package com.spring;  
  
import java.io.FileNotFoundException;  
import java.io.IOException;  
import java.util.ArrayList;  
import java.util.List;  
import java.util.Map;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import org.json.JSONObject;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.http.MediaType;  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.bind.annotation.ResponseBody;  
import org.springframework.web.context.ContextLoader;  
import org.springframework.web.context.WebApplicationContext;  
import org.springframework.web.context.support.WebApplicationContextUtils;  
import org.springframework.web.servlet.ModelAndView;  
  
@Controller  
@RequestMapping(value = "/spring")  
public class Action {  
  
    @Autowired  
    Teacher teacher;  
    // spring   restful     
      
    @ResponseBody  
    @RequestMapping(value = "/rest/{ownerId}.do", method = RequestMethod.GET)  
    public String findOwner(@PathVariable String ownerId, Model model,  
            HttpServletResponse rep) throws IOException {  
        return ownerId;  
    }  
  
    @RequestMapping(value = "/test.do", method = RequestMethod.GET)  
    public String testa(Model model, HttpServletResponse rep)  
            throws IOException {  
        model.addAttribute("abc", "efd");  
        model.addAttribute(teacher);  
        return "a";  
    }  
  
    @ResponseBody  
    //      @ResponseBody       teacher     3.2                   
    @RequestMapping(value = "/testb.do", method = RequestMethod.GET)  
    public String testb(Model model, HttpServletResponse rep,  
            HttpServletRequest req, String ex) throws IOException {  
        // WEB   SPRING    
        WebApplicationContext wac = WebApplicationContextUtils  
                .getRequiredWebApplicationContext(req.getServletContext());  
        return new JSONObject(wac.getBean(Teacher.class)).toString();  
    }  
  
    @ResponseBody  
    @RequestMapping(value = "/post.do", method = RequestMethod.POST)  
    public String post(Model model, HttpServletResponse rep,  
            HttpServletRequest req, String ex) throws IOException {  
        return new JSONObject(req.getParameterMap()).toString();  
    }  
  
}
  
再ユニットテストコード
import java.awt.print.Printable;  
import java.io.IOException;  
  
import javax.servlet.http.HttpServletResponse;  
  
import org.junit.Before;  
import org.junit.Test;  
import org.junit.runner.RunWith;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.http.MediaType;  
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.ResultHandler;  
import org.springframework.test.web.servlet.ResultMatcher;  
import org.springframework.ui.Model;  
import org.springframework.test.context.transaction.TransactionConfiguration;  
import org.springframework.transaction.annotation.Transactional;  
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;  
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;  
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;  
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.context.WebApplicationContext;  
  
@RunWith(SpringJUnit4ClassRunner.class)  
@WebAppConfiguration  
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })  
//                                     
@TransactionConfiguration(defaultRollback = true)  
//    XML        ~~~           
@Transactional  
public class ExampleTests {  
  
    @Autowired  
    private WebApplicationContext wac;  
  
    private MockMvc mockMvc;  
  
    @Before  
    public void setup() {  
        // webAppContextSetup      static import  
        // webAppContextSetup    WEB      fileter       listenCLASS  
        // WebApplicationContext context =  
        // ContextLoader.getCurrentWebApplicationContext();  
        //                     
        this.mockMvc = webAppContextSetup(this.wac).build();  
    }  
  
    @Test  
        //              
        @Rollback(false)  
    public void ownerId() throws Exception {  
        mockMvc.perform((get("/spring/rest/4.do"))).andExpect(status().isOk())  
                .andDo(print());  
    }  
  
    @Test  
    public void test() throws Exception {  
        mockMvc.perform((get("/spring/test.do"))).andExpect(status().isOk())  
                .andDo(print())  
                .andExpect(model().attributeHasNoErrors("teacher"));  
    }  
  
    @Test  
    public void testb() throws Exception {  
        mockMvc.perform((get("/spring/testb.do"))).andExpect(status().isOk())  
                .andDo(print())