2、spring boot + Maven + Restful(get,post,put,delete) 基本用例及Junit测试

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29451823/article/details/82669579
  • 实例目录
  • 这里写图片描述
    -
  • 查询用例
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    /**
     * 查询用例测试
     * @throws Exception
     */
    @Test
    public void whenGenInfoSuccess() throws Exception {
        String result = mockMvc.perform(get("/user/1")//请求类型
                .contentType(MediaType.APPLICATION_JSON_UTF8))//请求编码
                .andExpect(status().isOk())//验证状态是否为200
                .andExpect(jsonPath("$.username").value("tom"))//验证username是否为tom
                .andReturn().getResponse().getContentAsString();//添加返回值
                System.out.println(result);
    }
}
  • UserController.java
@RestController
@RequestMapping("/user")
public class UserController {
    /**
     *get添加{id:\\d+}表示id只能为数字
     *@PathVariable 表示id参数对应为url请求id字段
     */
    @GetMapping("/{id:\\d+}")
    public User getInfo(@PathVariable(name = "id") String id) {
        System.out.println("进入getInfo服务");
        User user = new User();
        user.setUsername("tom");
        return user;
    }
}
  • 查询分页用例
    UserController.java
    /**
     * page:从第几页开始,默认为0
     * size:每页显示数据条数,默认为20
     * sort:排序相关的信息,ASC和DESC
     * 指定参数名称@RequestParam(value = "usename", required = false     ,defaultValue = "tom")注意与@PathVariable的区别
     * @param condition
     * @param pageable
     * @return
     */
    @GetMapping
    public List<User> query(UserQueryCondition condition,@PageableDefault(page = 2 ,size =17, sort = "asc") Pageable pageable) {
        //反射的一个tostring工具
        System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE)); 
        System.out.println(pageable.getPageSize());
        System.out.println(pageable.getPageNumber());
        System.out.println(pageable.getSort());
        List<User> users = new ArrayList<>();
        users.add(new User());
        users.add(new User());
        users.add(new User());
        users.add(new User());
        return users;
    }

实体类User.java

package com.imooc.dto;

import java.util.Date;

import javax.validation.constraints.Past;

import org.hibernate.validator.constraints.NotBlank;

import com.fasterxml.jackson.annotation.JsonView;

import volidator.MyConstraint;

/**
 * 
 * @author caijiajun
 * @date   2018年8月31日
 */
public class User {

    private String username;
    private Integer id;
    private String password;
    private Date date;

    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 getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}

分页查询用例测试

    @Test
    public void whenQuerySuccess() throws Exception {
        String result = mockMvc.perform(get("/user")//模拟一个request请求
                .param("username", "join")
                .param("age", "18")
                .param("ageTo", "60")
                .param("xxx", "yyy")
                //查询第三页,每页返回15条数据,返回结果按照age的降序排序
/*              .param("size", "15")
                .param("page", "3")
                .param("sort", "age,desc")*/
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk())//期望返回的结果时isOK(200.andExpect(jsonPath("$.length()").value(4))//判断返回的是一个集合元素,并且数量为4,其中$代表返回的对象users
                .andReturn().getResponse().getContentAsString();    
                System.out.println(result);
    }

添加用例

    /**
     * 传入JSON格式,然后通过转化为pojo对象
     * 接受json,@RequestBody将其反序列化为pojo对象
     * @RequestBody 是写在方法参数前,作用于方法参数
     * @ResponseBody 是写在方法上,作用于方法返回值
     * @param user
     * @param errors
     * @return
     */
    @PostMapping
    public User create(@Valid @RequestBody User user) {
        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        System.out.println(user.getDate());
        user.setId(1);
        return user;
    }

添加用例测试

    /**
     * 添加测试
     */
    @Test
    public void whenCreateSuccess() throws Exception  {
        Date date = new Date();
        //避免格式问题,前后台传递时间使用时间戳
        System.out.println(date.getTime());
        String content = "{\"username\":\"tom\",\"password\":null,\"date\":"+date.getTime()+"}";
        String result = mockMvc.perform(post("/user").contentType(MediaType.APPLICATION_JSON_UTF8)
                                    .content(content))
                                    .andExpect(status().isOk())
                                    .andExpect(jsonPath("$.id").value(1))
                                    .andReturn().getResponse().getContentAsString();
        System.out.println(result);
    }
  • 更新用例
    controller
    /**
     * 更新
     * @param user
     * @param errors
     * @return
     */
    @PutMapping("/{id:\\d+}")
    public User update(@Valid @RequestBody User user) {
        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        System.out.println(user.getDate());
        user.setId(1);
        return user;
    }

更新用例测试

    /**
     * 更新测试
     * @throws Exception
     */
    @Test
    public void whenUpdateSuccess() throws Exception  {
        Date date = new Date();
        String content = "{\"id\":\"1\",\"username\":\"tom\",\"password\":null,\"date\":"+date.getTime()+"}";
        String result = mockMvc.perform(put("/user/1").contentType(MediaType.APPLICATION_JSON_UTF8)
                                    .content(content))
                                    .andExpect(status().isOk())
                                    .andExpect(jsonPath("$.id").value(1))
                                    .andReturn().getResponse().getContentAsString();
        System.out.println(result);
    }
  • 删除用例
    @DeleteMapping("/{id:\\d+}")
    public void delete(@PathVariable(name = "id") String id) {
        System.out.println("删除成功");
    }

删除用例测试

    /**
     * 删除测试
     * @throws Exception
     */
    @Test
    public void whenDeleteSuccess() throws Exception  {
        mockMvc.perform(delete("/user/1")
                        .contentType(MediaType.APPLICATION_JSON_UTF8))
                        .andExpect(status().isOk());
    }
  • 404错误状态测试
    @Test
    /**
     *404测试
     * @throws Exception
     */
    public void whenGenInfoFail() throws Exception {
        mockMvc.perform(get("/user/a")
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().is4xxClientError());

    }

猜你喜欢

转载自blog.csdn.net/qq_29451823/article/details/82669579