48. spring boot单元测试restfull API【从零开始学Spring Boot】

这一节我们使用SpringMVC来实现一组对User对象操作的RESTful API,配合注释详细说明在Spring MVC中如何映射HTTP请求、如何传参、如何编写单元测试。

* RESTful API具体设计如下:*

请求类型

URL

功能说明

GET

/users

查询用户列表

POST

/users

创建一个用户

GET

/users/id

根据id查询一个用户

PUT

/users/id

根据id更新一个用户

DELETE

/users/id

根据id删除一个用户

 

User实体定义:

publicclass User {

     privatelongid;

     private Stringname;

     private Integerage;

     // 省略setter和getter

}

实现对User对象的操作接口:

package com.kfit.controller;

 

import java.util.ArrayList;

import java.util.Collections;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

importorg.springframework.web.bind.annotation.PathVariable;

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

importorg.springframework.web.bind.annotation.RequestMethod;

importorg.springframework.web.bind.annotation.RestController;

import com.kfit.demo.User;

 

@RestController

@RequestMapping(value="/users")//通过这里配置使下面的映射都在/users下  

publicclass UserController {

      

       //这里为了方便测试,直接将数据存储在map中,实际请从数据库获取.

       privatestaticMap<Long,User>users = Collections.synchronizedMap(newHashMap<Long,User>());

      

       /**

        *返回所有的用户.

        *@return

        */

   @RequestMapping(value="", method=RequestMethod.GET)

   public List<User> getUserList() {

        // 处理"/users/"的GET请求,用来获取用户列表

        // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递

        List<User> r = newArrayList<User>(users.values());

        returnr;

   }

   

   @RequestMapping(value="/{id}",method=RequestMethod.GET)

   public User getUser(@PathVariable Longid) {

        // 处理"/users/{id}"的GET请求,用来获取url中id值的User信息

        // url中的id可通过@PathVariable绑定到函数的参数中

        returnusers.get(id);

   }

      

   /**

    * post保存用户.

    *@param user

    *@return

    */

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

   public String postUser(Useruser){

          // 处理"/users/"的POST请求,用来创建User

          //@ModelAttribute User user

        // 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数

          users.put(user.getId(),user);

          return"success";

   }

   

   /**

    *使用put进行更新用户.

    *@param id

    *@param user

    *@return

    */

   @RequestMapping(value="/{id}",method=RequestMethod.PUT)

   public String putUser(@PathVariable Longid,Useruser){

          // 处理"/users/{id}"的GET请求,用来获取url中id值的User信息

           User u = users.get(id);

         u.setName(user.getName());

         u.setAge(user.getAge());

         users.put(id,u);

          return"success";

   }

   

   /**

    *使用delete删除用户.

    *@param id

    *@return

    */

   @RequestMapping(value="/{id}", method=RequestMethod.DELETE)

   public String deleteUser(@PathVariable Longid) {

        // 处理"/users/{id}"的DELETE请求,用来删除User

        // url中的id可通过@PathVariable绑定到函数的参数中

        users.remove(id);

        return"success";

   }

   

}

 

下面针对该Controller编写测试用例验证正确性,具体如下。当然也可以通过浏览器插件等进行请求提交验证:






 

package com.kfit.demo;

 

import org.junit.Before;

import org.junit.Test;

import org.junit.runner.RunWith;

importorg.springframework.boot.test.SpringApplicationConfiguration;

importorg.springframework.mock.web.MockServletContext;

importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;

importorg.springframework.test.context.web.WebAppConfiguration;

importorg.springframework.test.web.servlet.MockMvc;

importorg.springframework.test.web.servlet.RequestBuilder;

importorg.springframework.test.web.servlet.request.MockMvcRequestBuilders;

importorg.springframework.test.web.servlet.result.MockMvcResultMatchers;

importorg.springframework.test.web.servlet.setup.MockMvcBuilders;

 

import com.kfit.controller.UserController;

 

@RunWith(SpringJUnit4ClassRunner.class)

@SpringApplicationConfiguration(classes=MockServletContext.class)//MockServletContext.class

@WebAppConfiguration

publicclass UserControllerTestextendsMockMvcResultMatchers{

      

       //模拟mvc对象类.

       private MockMvcmvc;

      

       @Before

       publicvoid setup(){

              /*

               * MockMvcBuilders使用构建MockMvc对象.

               */

              mvc =MockMvcBuilders.standaloneSetup(new UserController()).build();

       }

      

       @Test

       publicvoidtestUserController()throws Exception{

              RequestBuilderrequest =null;

              //1. get 以下user列表,应该为空》

      

              //1、构建一个get请求.

              request =MockMvcRequestBuilders.get("/users");

              mvc.perform(request)

                     .andExpect(status().isOk())

                     .andExpect(content().string("[]"))

                     ;

              System.out.println("UserControllerTest.testUserController().get");

             

              // 2、post提交一个user

              request =MockMvcRequestBuilders.post("/users")

                                                                      .param("id","1")

                                                                      .param("name","林峰")

                                                                      .param("age","20")

                            ;

             

             

              mvc.perform(request).andExpect(status().isOk()).andExpect(content().string("success"));

 

              // 3、get获取user列表,应该有刚才插入的数据

              request =MockMvcRequestBuilders.get("/users");

              mvc.perform(request).andExpect(status().isOk()).andExpect(content().string("[{\"id\":1,\"name\":\"林峰\",\"age\":20}]"));

             

             

              // 4、put修改id为1的user

        request = MockMvcRequestBuilders.put("/users/1")

                .param("name","林则徐")

                .param("age","30");

        mvc.perform(request)

                .andExpect(content().string("success"));

       

        // 5、get一个id为1的user

        request = MockMvcRequestBuilders.get("/users/1");

        mvc.perform(request)

                .andExpect(content().string("{\"id\":1,\"name\":\"林则徐\",\"age\":30}"));

             

       

       

    // 6del删除id为1的user

        request = MockMvcRequestBuilders.delete("/users/1");

        mvc.perform(request)

                .andExpect(content().string("success"));

 

        // 7、get查一下user列表,应该为空

        request = MockMvcRequestBuilders.get("/users");

        mvc.perform(request)

                .andExpect(status().isOk())

                .andExpect(content().string("[]"));

       

       }

      

}

     至此,我们通过引入web模块(没有做其他的任何配置),就可以轻松利用Spring MVC的功能,以非常简洁的代码完成了对User对象的RESTful API的创建以及单元测试的编写。


购买完整视频,请前往:http://www.mark-to-win.com/TeacherV2.html?id=287