您的位置:首页 > 编程语言 > Java开发

Spring mvc 之Junit 单元测试 Controller中方法

2018-01-05 18:02 399 查看

               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)
176de
;

        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
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: