【Spring Security OAuth2笔记系列】- 【使用Spring MVC开发RESTful API】 查询请求

查询请求

本章内容

  • 如何编写测试用例
  • 常用注解

    • RestController 提供RestAPI
    • RequestMapping及变体。映射http请求到java方法(变体下一章节讲解)
    • RequestParam 映射请求参数到java方法的参数
    • PageableDefault 指定分页参数的默认值

      是spring data里面的,如果不使用该框架作为处理层,则不需要该对象
      配合Pageable对象使用

如何编写测试用例

使用以下依赖

testCompile('org.springframework.boot:spring-boot-starter-test')

编写测试用例环境

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
    @Autowired
    private WebApplicationContext wac;

    // 伪造的mvc不会真正去启动项目?
    // 相对来说会比直接启用项目要快
    private MockMvc mockMvc;

    @Before
    public void setup() {
        // befor 注解,每个测试用例执行前都会执行
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }
}

编写一个查询用户的测试用例

// 查询成功的测试用例
@Test
public void whenQuerySuccess() throws Exception {
    mockMvc
            // 发起请求
            .perform(MockMvcRequestBuilders.get("/user")
                    // 添加请求头为json
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
            )
            // 期望的结果
            // 这里期望返回的http状态码为200
            .andExpect(MockMvcResultMatchers.status().isOk())
            // 从返回的结果中(json)获取长度,期望长度为3
            .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3))
    ;
}

jsonPath

MockMvcResultMatchers.jsonPath("$.length()" 里面的语法是从哪里来的?

查看jsonpath函数源码,方法说明上写着一个连接https://github.com/jayway/JsonPath 点击之后跳转到了https://github.com/json-path/JsonPath

看这里说使用说明文档,发现这里的语法就是该包的使用

扫描二维码关注公众号,回复: 2780106 查看本文章

编写一个restfull api

@RestController
public class UserController {
    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public List<User> query(@RequestParam() String username) {
        List<User> users = new ArrayList<>();
        users.add(new User());
        users.add(new User());
        users.add(new User());
        return users;
    }
}

---------------------- 说明 -------------------------
com.example.demo.dto.User  用来与前端返回的对象放在dto中

测试用例需要修改

@Test
  public void whenQuerySuccess() throws Exception {
      mockMvc
              .perform(MockMvcRequestBuilders.get("/user")
                      // 传递参数
                      .param("username", "mrcode")
                      .contentType(MediaType.APPLICATION_JSON_UTF8)
              )
              .andExpect(MockMvcResultMatchers.status().isOk())
              .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3))
      ;
  }

@RequestParam 注解说明

有以下作用:
1. 对参数进行别名的设置(默认与方法入参名一致)
2. 对参数控制是否必须(默认必须)

@RequestParam(required = true,name = "xxx") String username

上面的注解作用是:username 必须,且前段传递参数名必须为 xxx;

对查询方法进行改造

查询条件一般是多条件,使用封装成一个对象

public class UserQueryCondition {
    private String username;
    private int age;
    private int ageTo;
    private String xxx;

改写服务,这里使用了一个工具类,感觉还可以,故意记录下;

@RequestMapping(value = "/user", method = RequestMethod.GET)
 public List<User> query(UserQueryCondition condition) {
     // compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.7'
     // 一个反射工具类,这里把对象变成一个字符串,支持多种展示形式
     System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE));

测试用例也需要添加查询条件,打印的结果如下

com.example.demo.dto.UserQueryCondition@7f9e8421[
  username=mrcode
  age=1
  ageTo=3
  xxx=test
]

猜你喜欢

转载自blog.csdn.net/mr_zhuqiang/article/details/81502532