轉:Spring mvc 之Junit 單元測試 Controller中方法

  Springmvc 之Junit 單元測試
1.   首先引入測試的jar包。
1.1因爲我用的ide是eclipse,現只介紹eclipse中junit的使用。首先引用eclipse中自帶的junit,

方法:

右鍵項目—>property---->如下圖所示

 

1.2     因爲是要測試junit對springmvc中Controller的單元測試,故要引入Spring-test jar包

引入方式

<!-- Spring  單元測試包 -->

      <dependency>

        <groupId>org.springframework</groupId>

        <artifactId>spring-test</artifactId>

        <version>${spring.version}</version>

        <!-- 表是測試時才引用,發佈時去掉 -->

        <scope>test</scope>

 

2.   建立測試的Controller,代碼如下
packageorg.xxz.controller;

 

importjava.util.List;

 

importjavax.annotation.Resource;

 

importorg.springframework.stereotype.Controller;

importorg.springframework.ui.ModelMap;

importorg.springframework.web.bind.annotation.RequestBody;

importorg.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

importorg.springframework.web.bind.annotation.ResponseBody;

importorg.xxz.domain.Comment;

importorg.xxz.service.CommentService;

 

importcom.alibaba.fastjson.JSONObject;

 

@Controller

public class WelcomeController{

   

    @Resource

    private CommentService commentService;

   

    @RequestMapping(value = "/test")

    public String test(ModelMap model) {

        model.put("key", "helloqq-comment");

        return "test";

    }

   

    @RequestMapping(value = "/test1")

    @ResponseBody

    public String test1() {

        return "test";

    }

    /**單參數測試get**/

    @RequestMapping(value ="/comment")

    public String comment(String itemId,ModelMap model) {

        List<Comment> itemComments =commentService.findCommentByItemId(itemId, 1, 10);

        model.put("itemComments",itemComments);

        return "comment";

    }

    /**responseBody 測試**/

    @RequestMapping(value ="/comment1")

    @ResponseBody

    public String comment1(String itemId,ModelMap model) {

        List<Comment> itemComments =commentService.findCommentByItemId(itemId, 1, 10);

        model.put("itemComments",itemComments);

        return "comment";

    }

    /**post方式測試Controller**/

    @RequestMapping(value ="/comment2",method=RequestMethod.POST)

    public String comment2(String itemId,ModelMap model) {

        List<Comment> itemComments =commentService.findCommentByItemId(itemId, 1, 10);

        model.put("itemComments",itemComments);

        return "comment";

    }

    /**多參數get測試**/

    @RequestMapping(value ="/comment4")

    public String comment4(String itemId,Stringa, ModelMap model) {

        List<Comment> itemComments =commentService.findCommentByItemId(itemId, 1, 10);

        model.put("itemComments",itemComments);

        System.out.println(itemId +"##########"+ a);

        return "comment";

    }

 

    /**多參數Post測試**/

    @RequestMapping(value ="/comment5",method=RequestMethod.POST)

    public String comment5(String itemId,Stringa, ModelMap model) {

        List<Comment> itemComments =commentService.findCommentByItemId(itemId, 1, 10);

        model.put("itemComments",itemComments);

        System.out.println(itemId +"##########"+ a);

        return "comment";

    }

    /**進行增加操作**/

    @RequestMapping(value ="/comment6",method=RequestMethod.POST)

    public String comment6(String itemId,Stringa, ModelMap model) {

          System.out.println(itemId+a);

          Commentc=new Comment();

          c.setId("666");

          c.setContentId("666");

          c.setParentCommentId("6666");

          c.setCustomerId("666");

          try{

                 commentService.addcomment(c);

              } catch (Exception e) {

                     e.printStackTrace();

              }

         

        return "success";

    }

    /**測試傳輸數據爲json格式**/

    @RequestMapping(value ="/comment7",method=RequestMethod.POST)

    public String comment7(@RequestBodyJSONObject jobj , ModelMap model) {  

          System.out.println(jobj.get("id"));

          //System.out.println(jobj);

        return "success";

    }

}

 

3.   根據源Controller建立相應的測試類 WelcomeControllerTest.java
3.1首先介紹一下我的文檔結構如下圖所示,我建立了一個專門測試的包,命名爲test。所有的測試代碼放於此,方便管理和查看。

 

3.2 使用Eclipse自帶工具生成相應的測試類    右擊要測試的Controller————>選擇Junit Test Case(如果沒有的話,選擇Other 搜索 junit即可找到)

在此我這隻勾選了setup(), 然後點擊下一步,勾選相應的方法進行測試。點擊完成就會生成相應的測試類 WelcomeControllerTest.java。

 

3.3. WelcomeControllerTest.java 代碼如下

package org.xxz.test;

 

importstaticorg.junit.Assert.*;

 

import java.util.List;

 

import javax.annotation.Resource;

 

import org.junit.Before;

import org.junit.Ignore;

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.web.servlet.MockMvc;

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

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

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

import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

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

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.context.WebApplicationContext;

import org.xxz.domain.Comment;

import org.xxz.service.CommentService;

 

import com.alibaba.fastjson.JSONObject;

 

importstaticorg.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

importstaticorg.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

 

/**

* @author :hanzl

* @version創建時間:2018年1月5日上午9:53:45

*/

 

publicclassWelcomeControllerTest extends BaseJunitTest {

 @Resource

 privateCommentService commentService;

 

 @Autowired 

 privateWebApplicationContext webApplicationContext;

 privateMockMvc mockMvc;

 

   //方法執行前初始化數據

   @Before

   publicvoid setUp() throws Exception {

      mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext ).build();

   }

   @Ignore//忽略此方法

   publicvoid testTest() {

      System.out.println("hello");

   }

 

   @Ignore//忽略此方法

   publicvoid testTest1() {

      fail("Not yet implemented");

   }

 

   @Test

   publicvoid testComment() throws Exception {

      /***第一種測試方式,直接copy原方法中邏輯代碼  直接輸出結果*/

      /*List<Comment> itemComments =commentService.findCommentByItemId("1", 1, 10);

      for(Commentc:itemComments){

        System.out.println(c.getContent());

      }*/

      /**第二種方法,利用MockMVC模擬get方法訪問**/

      /*MockHttpServletRequestBuildermockHttpServletRequestBuilder = MockMvcRequestBuilders.get("/comment" );

      mockHttpServletRequestBuilder.param("itemId", "1" ); //要傳入的參數

      ResultActionsresultActions = mockMvc.perform( mockHttpServletRequestBuilder ); 

        resultActions.andExpect(status().isOk());*/

       

        /**第三種測試方法針對get請求   Controller默認的請求方法是get*/

      /*String responseString = mockMvc.perform(MockMvcRequestBuilders.get("/comment").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("itemId","1")  //數據的格式   .contentType(MediaType.APPLICATION_FORM_URLENCODED)   數據的格式請求的url,請求的方法是get.contentType(MediaType.APPLICATION_FORM_URLENCODED)  //數據的格式 .param("pcode","root")         //添加參數

        ).andExpect(status().isOk())    //返回的狀態是200

                .andDo(print())    //打印出請求和相應的內容

      .andReturn().getResponse().getContentAsString();

      System.out.println("哈哈哈"+responseString); //在Controller 中加 @ResponseBody 可輸出要返回的內容

     }*/

      /**第四種測試方法針對 Post請求    Controller註解加上 method=RequestMethod.POST  只需要將第三種方法的get 換爲post即可*/

      /*String responseString = mockMvc.perform(MockMvcRequestBuilders.post("/comment").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("itemId","1")  //數據的格式   .contentType(MediaType.APPLICATION_FORM_URLENCODED)   數據的格式請求的url,請求的方法是get.contentType(MediaType.APPLICATION_FORM_URLENCODED)  //數據的格式 .param("pcode","root")         //添加參數

              ).andExpect(status().isOk())    //返回的狀態是200

                      .andDo(print())    //打印出請求和相應的內容

             .andReturn().getResponse().getContentAsString();

           System.out.println("哈哈哈"+responseString); //在Controller 中加 @ResponseBody 可輸出要返回的內容

       */  

      /**傳入多個參數測試get*/

      /*String responseString = mockMvc.perform(MockMvcRequestBuilders.get("/comment").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("itemId","1").param("a", "hanzl")  //數據的格式   .contentType(MediaType.APPLICATION_FORM_URLENCODED)   數據的格式請求的url,請求的方法是get.contentType(MediaType.APPLICATION_FORM_URLENCODED)  //數據的格式 .param("pcode","root")         //添加參數

              ).andExpect(status().isOk())    //返回的狀態是200

                      .andDo(print())    //打印出請求和相應的內容

             .andReturn().getResponse().getContentAsString();

           System.out.println("哈哈哈"+responseString);

   }*/

    /**傳入多個參數測試post**/

   /*String responseString = mockMvc.perform(MockMvcRequestBuilders.post("/comment5").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("itemId","1").param("a", "hanzl")  //數據的格式   .contentType(MediaType.APPLICATION_FORM_URLENCODED)   數據的格式請求的url,請求的方法是get.contentType(MediaType.APPLICATION_FORM_URLENCODED)  //數據的格式 .param("pcode","root")         //添加參數

           ).andExpect(status().isOk())    //返回的狀態是200

                   .andDo(print())    //打印出請求和相應的內容

         .andReturn().getResponse().getContentAsString();

        System.out.println("哈哈哈"+responseString);

       }*/

  

   /**測試數據庫添加數據測試**/

   /*String responseString = mockMvc.perform(MockMvcRequestBuilders.post("/comment6").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("itemId","1").param("a", "hanzl")  //數據的格式   .contentType(MediaType.APPLICATION_FORM_URLENCODED)   數據的格式請求的url,請求的方法是get.contentType(MediaType.APPLICATION_FORM_URLENCODED)  //數據的格式 .param("pcode","root")         //添加參數

           ).andExpect(status().isOk())    //返回的狀態是200

                   .andDo(print())    //打印出請求和相應的內容

         .andReturn().getResponse().getContentAsString();

        System.out.println("哈哈哈"+responseString);

       }*/

     /**測試請求參數爲json時**/

     Comment c=new Comment();

     c.setId("666");

     c.setContentId("666");

     c.setParentCommentId("6666");

     c.setCustomerId("666");

     String requestJson = JSONObject.toJSONString(c);

     String responseString = mockMvc.perform( MockMvcRequestBuilders.post("/comment7").contentType(MediaType.APPLICATION_JSON).content(requestJson)  //數據的格式   .contentType(MediaType.APPLICATION_FORM_URLENCODED)   數據的格式請求的url,請求的方法是get.contentType(MediaType.APPLICATION_FORM_URLENCODED)  //數據的格式 .param("pcode","root")         //添加參數

           ).andExpect(status().isOk())    //返回的狀態是200

                   .andDo(print())    //打印出請求和相應的內容

         .andReturn().getResponse().getContentAsString();

        System.out.println("哈哈哈"+responseString);

       }

}

4.   建立測試基類BaseJunitTest.java,加載相應的基本信息,方便拓展,WelcomeComtrollerTest繼承BaseJunitTest.java
BaseJunitTest 代碼如下:

 

解釋說明:

@webappconfiguration是一級註釋,用於聲明一個ApplicationContext集成測試加載WebApplicationContext。作用是模擬ServletContext

@ContextConfiguration:因爲controller,component等都是使用註解,需要註解指定spring的配置文件,掃描相應的配置,將類初始化等

 

package org.xxz.test;

 

import org.junit.runner.RunWith;

import org.springframework.test.context.ContextConfiguration;

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

import org.springframework.test.context.transaction.TransactionConfiguration;

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

import org.springframework.transaction.annotation.Transactional;

/**

* @author :hanzl

* @version創建時間:2018年1月5日上午10:21:45

*/

@RunWith(SpringJUnit4ClassRunner.class)

//配置事務的回滾,對數據庫的增刪改都會回滾,便於測試用例的循環利用

@TransactionConfiguration(transactionManager= "transactionManager", defaultRollback = true)

@Transactional

@WebAppConfiguration

@ContextConfiguration(locations = { "classpath:spring.xml","classpath:spring-mvc.xml"})

publicclassBaseJunitTest {

 

}

5.   實際測試 spring mvc 請求方式爲get(spring mvc默認請求方式爲get)參數爲一個
5.1   Controller測試代碼方法:
/**單參數測試get**/

    @RequestMapping(value ="/comment")

    public String comment(String itemId,ModelMap model) {

        List<Comment> itemComments =commentService.findCommentByItemId(itemId, 1, 10);

        model.put("itemComments",itemComments);

        return "comment";

}

5.2             測試類中代碼方法:
/***第一種測試方式,直接copy原方法中邏輯代碼  直接輸出結果*/

                   /*List<Comment>itemComments = commentService.findCommentByItemId("1", 1, 10);

                   for(Commentc:itemComments){

                            System.out.println(c.getContent());

                   }*/

 

6.   利用利用MockMVC模擬get方法訪問測試
6.1 Controller中方法代碼不用變
6.2 測試類 中方法代碼如下:
MockHttpServletRequestBuildermockHttpServletRequestBuilder = MockMvcRequestBuilders.get("/comment" );

                   mockHttpServletRequestBuilder.param("itemId", "1" ); //要傳入的參數

                   ResultActionsresultActions = mockMvc.perform( mockHttpServletRequestBuilder ); 

       resultActions.andExpect( status().isOk());

7.    第三種測試方法針對get請求   Controller默認的請求方法是get
7.1 Controller中方法不變
7.2 測試類中代碼如下:
StringresponseString= mockMvc.perform(MockMvcRequestBuilders.get("/comment").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("itemId","1")  //數據的格式   .contentType(MediaType.APPLICATION_FORM_URLENCODED)   數據的格式請求的url,請求的方法是get.contentType(MediaType.APPLICATION_FORM_URLENCODED)  //數據的格式.param("pcode","root")         //添加參數

       ).andExpect(status().isOk())    //返回的狀態是200

               .andDo(print())    //打印出請求和相應的內容

       .andReturn().getResponse().getContentAsString();

              System.out.println("哈哈哈"+responseString);

 

8.   第四種測試方法 針對 Post請求    Controller註解加上  method=RequestMethod.POST  只需要將第三種方法的get 換爲post即可
8.1 Controller中代碼:
/**post方式測試Controller**/

   @RequestMapping(value = "/comment2",method=RequestMethod.POST)

   public String comment2(String itemId, ModelMap model) {

       List<Comment> itemComments =commentService.findCommentByItemId(itemId, 1, 10);

       model.put("itemComments", itemComments);

       return "comment";

}

8.2測試方法代碼:
StringresponseString = mockMvc.perform(MockMvcRequestBuilders.post("/comment").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("itemId","1")  //數據的格式   .contentType(MediaType.APPLICATION_FORM_URLENCODED)   數據的格式請求的url,請求的方法是get.contentType(MediaType.APPLICATION_FORM_URLENCODED)  //數據的格式.param("pcode","root")         //添加參數

                           ).andExpect(status().isOk())    //返回的狀態是200

                                   .andDo(print())    //打印出請求和相應的內容

                          .andReturn().getResponse().getContentAsString();

                                     System.out.println("哈哈哈"+responseString);

 

9.   測試get方法傳入多個參數
9.1 Controller中代碼:
/**多參數get測試**/

   @RequestMapping(value= "/comment4")

   publicString comment4(String itemId,String a, ModelMap model) {

        List<Comment> itemComments = commentService.findCommentByItemId(itemId, 1, 10);

        model.put("itemComments", itemComments);

        System.out.println(itemId + "##########"+ a);

        return"comment";

}

9.2             測試方法代碼:
String responseString = mockMvc.perform(MockMvcRequestBuilders.get("/comment").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("itemId","1").param("a", "hanzl")  //數據的格式    .contentType(MediaType.APPLICATION_FORM_URLENCODED)   數據的格式請求的url,請求的方法是get.contentType(MediaType.APPLICATION_FORM_URLENCODED)  //數據的格式.param("pcode","root")         //添加參數

                           ).andExpect(status().isOk())    //返回的狀態是200

                                   .andDo(print())    //打印出請求和相應的內容

                         .andReturn().getResponse().getContentAsString();

                                     System.out.println("哈哈哈"+responseString);

10.             傳入多個參數測試post
10.1 Controller中代碼
/**多參數Post測試**/

   @RequestMapping(value= "/comment5",method=RequestMethod.POST)

   publicString comment5(String itemId,String a, ModelMap model) {

        List<Comment> itemComments = commentService.findCommentByItemId(itemId, 1, 10);

        model.put("itemComments", itemComments);

        System.out.println(itemId + "##########"+ a);

       return"comment";

}

10.2  測試方法中代碼:
String responseString = mockMvc.perform(MockMvcRequestBuilders.post("/comment5").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("itemId","1").param("a", "hanzl")  //數據的格式   .contentType(MediaType.APPLICATION_FORM_URLENCODED)   數據的格式請求的url,請求的方法是get.contentType(MediaType.APPLICATION_FORM_URLENCODED)  //數據的格式 .param("pcode","root")         //添加參數

              ).andExpect(status().isOk())    //返回的狀態是200

                      .andDo(print())    //打印出請求和相應的內容

            .andReturn().getResponse().getContentAsString();

                    System.out.println("哈哈哈"+responseString);

       }

 

11.             測試數據庫添加數據測試測試session回滾
11.1 Controller中代碼:
@RequestMapping(value = "/comment6",method=RequestMethod.POST)

   publicString comment6(String itemId,String a, ModelMap model) {

     System.out.println(itemId+a);

     Comment c=new Comment();

     c.setId("666");

     c.setContentId("666");

     c.setParentCommentId("6666");

     c.setCustomerId("666");

     try {

        commentService.addcomment(c);

      }catch(Exception e) {

        e.printStackTrace();

      }

    

        return"success";

}

11.2        測試方法代碼不變
12.             測試請求數據爲json時,參數爲json時
12.1Controller中方法代碼:
/**測試傳輸數據爲json格式**/

   @RequestMapping(value= "/comment7",method=RequestMethod.POST)

   publicString comment7(@RequestBody JSONObject jobj, ModelMap model){  

     System.out.println(jobj.get("id"));

     //System.out.println(jobj);

        return"success";

}

12.2測試中方法代碼:
/**測試請求參數爲json時**/

       Comment c=new Comment();

      c.setId("666");

      c.setContentId("666");

      c.setParentCommentId("6666");

      c.setCustomerId("666");

       String requestJson = JSONObject.toJSONString(c);

       String responseString = mockMvc.perform(MockMvcRequestBuilders.post("/comment7").contentType(MediaType.APPLICATION_JSON).content(requestJson)  //數據的格式   .contentType(MediaType.APPLICATION_FORM_URLENCODED)   數據的格式請求的url,請求的方法是get.contentType(MediaType.APPLICATION_FORM_URLENCODED)  //數據的格式.param("pcode","root")         //添加參數

             ).andExpect(status().isOk())    //返回的狀態是200

                      .andDo(print())    //打印出請求和相應的內容

            .andReturn().getResponse().getContentAsString();

                         System.out.println("哈哈哈"+responseString);

       }

 

13.             以上所有的情況均已試過,特別感謝兩篇文章在此貼下連接,如有不足,請見諒!
https://www.cnblogs.com/0201zcr/p/5756642.html

 

https://www.cnblogs.com/puyangsky/p/6661638.html
————————————————
版權聲明:本文爲CSDN博主「NO如果」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/hanzl1/article/details/78983939

發佈了12 篇原創文章 · 獲贊 121 · 訪問量 32萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章