1.1因为我用的ide是eclipse,现只介绍eclipse中junit的使用。首先引用eclipse中自带的junit,
方法:
右键项目—>property---->如下图所示
1.2 因为是要测试junit对springmvc中Controller的单元测试,故要引入Spring-test jar包
引入方式
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
<scope>testscope>
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
model.put("itemComments",itemComments);
return "comment";
}
/**responseBody 测试**/
@RequestMapping(value ="/comment1")
@ResponseBody
public String comment1(String itemId,ModelMap model) {
List
model.put("itemComments",itemComments);
return "comment";
}
/**post方式测试Controller**/
@RequestMapping(value ="/comment2",method=RequestMethod.POST)
public String comment2(String itemId,ModelMap model) {
List
model.put("itemComments",itemComments);
return "comment";
}
/**多参数get测试**/
@RequestMapping(value ="/comment4")
public String comment4(String itemId,Stringa, ModelMap model) {
List
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
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.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
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);
}
}
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 {
}
/**单参数测试get**/
@RequestMapping(value ="/comment")
public String comment(String itemId,ModelMap model) {
List
model.put("itemComments",itemComments);
return "comment";
}
/***第一种测试方式,直接copy原方法中逻辑代码 直接输出结果*/
/*List
for(Commentc:itemComments){
System.out.println(c.getContent());
}*/
MockHttpServletRequestBuildermockHttpServletRequestBuilder = MockMvcRequestBuilders.get("/comment" );
mockHttpServletRequestBuilder.param("itemId", "1" ); //要传入的参数
ResultActionsresultActions = mockMvc.perform( mockHttpServletRequestBuilder );
resultActions.andExpect( status().isOk());
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);
/**post方式测试Controller**/
@RequestMapping(value = "/comment2",method=RequestMethod.POST)
public String comment2(String itemId, ModelMap model) {
List
model.put("itemComments", itemComments);
return "comment";
}
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);
/**多参数get测试**/
@RequestMapping(value= "/comment4")
publicString comment4(String itemId,String a, ModelMap model) {
List
model.put("itemComments", itemComments);
System.out.println(itemId + "##########"+ a);
return"comment";
}
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测试**/
@RequestMapping(value= "/comment5",method=RequestMethod.POST)
publicString comment5(String itemId,String a, ModelMap model) {
List
model.put("itemComments", itemComments);
System.out.println(itemId + "##########"+ a);
return"comment";
}
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);
}
@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";
}
/**测试传输数据为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";
}
/**测试请求参数为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);
}
https://www.cnblogs.com/0201zcr/p/5756642.html
https://www.cnblogs.com/puyangsky/p/6661638.html