SpringBoot初体验:久闻大名,请多指教!(简单web项目+MockMvc单元测试)

来源:互联网 发布:脉冲信号 计数 单片机 编辑:程序博客网 时间:2024/06/05 11:51

环境说明

  • Windows 10 ver 1709
  • JDK 1.8.0_144
  • Maven 3.5.0
  • IDEA 2017.3.1
  • SpringBoot 1.5.9.RELEASE

创建项目(多图预警)

创建

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

代码展示

User.java

package xin.csqsx.pojo;/** * 包名 xin.csqsx.pojo * 类名 User * 类描述  用户实体类 * * @author dell * @version 1.0 * 创建日期 2017/12/14 * 时间 11:13 */public class User {    private Long id;    private String username;    private String password;    private Integer age;    public Long getId() {        return id;    }    public void setId(Long id) {        this.id = id;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }}

UserController.java

package xin.csqsx.restful;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import xin.csqsx.pojo.User;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;/** * 包名 xin.csqsx.restful * 类名 UserController * 类描述  设计user类的RESTFul的curd接口 * * @author dell * @version 1.0 * 创建日期 2017/12/14 * 时间 11:16 */@RestController@RequestMapping("/users")public class UserController {    /*    @RestController与@Controller之间的区别    前者默认该类的返回值都是json格式,后者需要配合@ResponseBody才能达到前者的功能     */    /**     * 创建线程安全的HashMap     */    private static Map<Long, User> users = new ConcurrentHashMap<>(16);    /**     * 类名 UserController     * 方法名 getUserList     * 返回值类型 java.util.List<xin.csqsx.pojo.User>     * 参数 []     * 方法描述 处理/users的get请求,用来获取用户列表     * 作者 dell     * 创建日期 2017/12/14     * 时间 11:26     */    @RequestMapping(value = "/", method = RequestMethod.GET)    public List<User> getUserList() {        return new ArrayList<>(users.values());    }    /**     * 类名 UserController     * 方法名 postUser     * 返回值类型 java.lang.String     * 参数 [user]     * 方法描述  处理/users的post请求,用来新增一个用户     * 作者 dell     * 创建日期 2017/12/14     * 时间 11:32     */    @RequestMapping(value = "/", method = RequestMethod.POST)    public String postUser(User user) {        users.put(user.getId(), user);        return "success";    }    /**     * 类名 UserController     * 方法名 getUserById     * 返回值类型 xin.csqsx.pojo.User     * 参数 [id]     * 方法描述  处理/users/id的get请求,用来查询id为指定id的用户的信息     * 作者 dell     * 创建日期 2017/12/14     * 时间 11:36     */    @RequestMapping(value = "/{id}", method = RequestMethod.GET)    public User getUserById(@PathVariable Long id) {        return users.get(id);    }    /**     * 类名 UserController     * 方法名 putUserById     * 返回值类型 java.lang.String     * 参数 [id]     * 方法描述  处理/users/id的put请求,用来更新id为指定id的用户的信息     * 作者 dell     * 创建日期 2017/12/14     * 时间 11:40     */    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)    public String putUserById(@PathVariable Long id) {        User user = users.get(id);        user.setUsername(user.getPassword());        user.setPassword(user.getAge() + "");        users.put(id, user);        return "success";    }    /**     * 类名 UserController     * 方法名 deleteUserById     * 返回值类型 java.lang.String     * 参数 [id]     * 方法描述  处理/users/id的delete请求,用来删除id为指定id的用户     * 作者 dell     * 创建日期 2017/12/14     * 时间 11:42     */    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)    public String deleteUserById(@PathVariable Long id) {        users.remove(id);        return "success";    }}

RestfulApplication.java

package xin.csqsx.restful;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** * 包名 xin.csqsx.restful * 类名 RestfulApplication * 类描述  使用SpringBoot完成一个简单的Restful风格的接口设计 * * @author dell * @version 1.0 * 创建日期 2017/12/14 * 时间 11:10 */@SpringBootApplicationpublic class RestfulApplication {    public static void main(String[] args) {        SpringApplication.run(RestfulApplication.class, args);    }}

UserControllerTest.java

package xin.csqsx.restful;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.http.MediaType;import org.springframework.test.context.junit4.SpringRunner;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;import org.springframework.test.web.servlet.result.MockMvcResultHandlers;import org.springframework.test.web.servlet.result.MockMvcResultMatchers;import org.springframework.test.web.servlet.setup.MockMvcBuilders;import org.springframework.web.context.WebApplicationContext;/** * 包名 xin.csqsx.restful * 类名 UserControllerTest * 类描述  UserController的单元测试类,使用mockMVC进行controller测试 * * @author dell * @version 1.0 * 创建日期 2017/12/14 * 时间 11:44 */@RunWith(SpringRunner.class)@SpringBootTest(classes = RestfulApplication.class)public class UserControllerTest {    @Autowired    private WebApplicationContext context;    private MockMvc mockMvc;    @Before    public void setUp() {        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();    }    /**     * 测试获取用户列表接口是否正常     */    @Test    public void testGetUserList() throws Exception {        mockMvc.perform(MockMvcRequestBuilders.get("/users/")                .contentType(MediaType.APPLICATION_JSON_UTF8)                .accept(MediaType.APPLICATION_JSON))                .andExpect(MockMvcResultMatchers.status().isOk())                .andDo(MockMvcResultHandlers.print());    }    /**     * 测试添加用户接口是否正常     */    @Test    public void testPostUser() throws Exception {        mockMvc.perform(MockMvcRequestBuilders.post("/users/")                .contentType(MediaType.APPLICATION_JSON_UTF8)                .accept(MediaType.APPLICATION_JSON)                .param("id", "123456")                .param("username", "mark")                .param("password", "12321")                .param("age", "12"))                .andExpect(MockMvcResultMatchers.status().isOk())                .andDo(MockMvcResultHandlers.print());    }    /**     * 测试通过id获取用户的接口是否正常     */    @Test    public void testGetUserById() throws Exception {        mockMvc.perform(MockMvcRequestBuilders.get("/users/123456")                .contentType(MediaType.APPLICATION_JSON_UTF8)                .accept(MediaType.APPLICATION_JSON))                .andExpect(MockMvcResultMatchers.status().isOk())                .andDo(MockMvcResultHandlers.print());    }    /**     * 测试修改用户的接口是否正常     */    @Test    public void testPutUserById() throws Exception {        mockMvc.perform(MockMvcRequestBuilders.put("/users/123456")                .contentType(MediaType.APPLICATION_JSON_UTF8)                .accept(MediaType.APPLICATION_JSON))                .andExpect(MockMvcResultMatchers.status().isOk())                .andDo(MockMvcResultHandlers.print());    }    /**     * 测试删除用户的接口是否正常     */    @Test    public void testDeleteUserById() throws Exception {        mockMvc.perform(MockMvcRequestBuilders.delete("/users/123456")                .contentType(MediaType.APPLICATION_JSON_UTF8)                .accept(MediaType.APPLICATION_JSON))                .andExpect(MockMvcResultMatchers.status().isOk())                .andDo(MockMvcResultHandlers.print());    }    /**     * 组合测试     */    @Test    public void testMain() throws Exception {        //添加一个用户        testPostUser();        //获取用户列表        testGetUserList();        //修改一个用户        testPutUserById();        //获取一个用户        testGetUserById();        //删除一个用户        testDeleteUserById();        //重新获取一个用户        testGetUserById();    }}

RestfulApplicationTests.java

package xin.csqsx.restful;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)@SpringBootTestpublic class RestfulApplicationTests {    @Test    public void contextLoads() {    }}

开始springBoot的学习了.
技术更新如此之快,除了时刻保持关注之外,如何能以不变应万变?
思想很重要,希望我能变得更强.


2017/12/14
Lucifer

原创粉丝点击