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
<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/puyangsky/p/6661638.html