Spring Boot构建RESTful API与单元测试(MockMvc)

感谢作者: http://blog.didispace.com/springbootrestfulapi/

参考:http://jinnianshilongnian.iteye.com/blog/2004660

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

RESTful API具体设计如下:

User实体类

/**
 * @author Ray
 * @date 2018/7/1 0001
 * User实体定义
 */
public class User {

    private Long id;
    private String name;
    private Integer age;

   // 省略setter和getter
}

配置控制器

/**
 * @author Ray
 * @date 2018/7/1 0001
 */
@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String index(){
        return "Hello World";
    }
}
/**
 * @author Ray
 * @date 2018/7/1 0001
 */
@RestController
@RequestMapping(value = "/users")  // 通过这里配置使下面的映射都在/users下,可去除
public class UserController {

    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<>());

    /**
     * 处理"/users/" 的GET请求,用来获取用户列表
     * 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<User> getUserList(){
        List<User> list = new ArrayList<>(users.values());
        return list;
    }

    /**
     * 处理"/users/" 的POST请求,用来创建User
     * 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数
     */
    @RequestMapping(value = "/", method = RequestMethod.POST)
    public String postUser(@ModelAttribute User user){
        users.put(user.getId(), user);
        return "success";
    }

    /**
     * 处理"/users/{id}" 的GET请求,用来获取url中id值得User信息
     * url中的id可通过@PathVariable绑定到函数的参数中
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User getUser(@PathVariable Long id){
        return users.get(id);
    }

    /**
     * 处理"/users/{id}" 的PUT请求, 用来更新User信息
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public String putUser(@PathVariable Long id, @ModelAttribute User user){
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);
        return "success";
    }

    /**
     * 处理"/users/{id}" 的DELETE请求,用来删除User
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id){
        users.remove(id);
        return "success";
    }
}


针对Controller编写测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter311ApplicationTests {

    private MockMvc mvc;

    @Before
    public void setUp(){
        mvc = MockMvcBuilders.standaloneSetup(
                new HelloController(),
                new UserController()
        ).build();
    }

    /**
     * 测试HelloController
     */
    @Test
    public void getHello() throws Exception {
        mvc.perform(get("/hello").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("Hello World")));
    }

    /**
     * 测试UserController
     */
    @Test
    public void testUserController() throws Exception {
        RequestBuilder request = null;

        // 1.get查一下user列表,应该为空 []
        request = get("/users/");
        mvc.perform(request)
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("[]")));

        // 2.post提交一个user
        request = post("/users/")
                .param("id", "1")
                .param("name", "测试")
                .param("age", "20");
        mvc.perform(request)
                .andExpect(content().string(equalTo("success")));

        // 3.get获取user列表,应该有刚才插入的数据
        request = get("/users/");
        mvc.perform(request)
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("[{\"id\":1,\"name\":\"测试\",\"age\":20}]")));

        // 4.put修改id为1的user
        request = put("/users/1")
                .param("name", "测试put")
                .param("age", "30");
        mvc.perform(request)
                .andExpect(content().string(equalTo("success")));

        // 5.get一个id为1的user
        request = get("/users/1");
        mvc.perform(request)
                .andExpect(content().string(equalTo("{\"id\":1,\"name\":\"测试put\",\"age\":30}")));

        // 6.del删除id为1的user
        request = delete("/users/1");
        mvc.perform(request)
                .andExpect(content().string(equalTo("success")));

        // 7.get查一下user列表,应该为空 []
        request = get("/users/");
        mvc.perform(request)
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("[]")));
    }
}

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

其中同时介绍了Spring MVC中最为常用的几个核心注解:@Controller,@RestController,RequestMapping

以及一些参数绑定的注解:@PathVariable,@ModelAttribute,@RequestParam等。

猜你喜欢

转载自blog.csdn.net/q343509740/article/details/80872089