单元测试
第一部分 固定格式
package com.internetCafes.controller;
import com.internetCafes.entity.login.LoginReq;
import com.internetCafes.entity.login.LoginRes;
import com.internetCafes.spms.ApplicationBootstrap;
import net.sf.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationBootstrap.class)
@WebAppConfiguration
public class DemoControllerTest {
protected static Logger logger = LoggerFactory.getLogger(DemoControllerTest.class);
@Autowired
protected WebApplicationContext context;
protected MockMvc mvc;
@Test
public void loginTest() throws Exception {
//1-请求数据
String url = "/sys/login";
LoginReq loginReq = new LoginReq(
"系统管理",
"admin",
"admin",
"captcha",
"uuid");
JSONObject content = JSONObject.fromObject(loginReq);
// 2-配置请求接口数据
RequestBuilder builder = MockMvcRequestBuilders
.post(url)
.content(content.toString())
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
// 2.5-构建MockMvc测试核心
mvc = MockMvcBuilders.webAppContextSetup(context).build();
// 3-请求接口 并的对数据进行处理
MvcResult mvcResult = mvc.perform(builder)
.andDo(MockMvcResultHandlers.print()) //对结果进行打印
.andExpect(status().isOk()) //属于断言对返回code进行对比
.andReturn(); //返回MvcResult
// 获取返回结果 body
String contentAsString = mvcResult.getResponse().getContentAsString();
// 4-结果值封装
JSONObject jsonObject = JSONObject.fromObject(contentAsString);
LoginRes result = (LoginRes) JSONObject.toBean(jsonObject, LoginRes.class);
logger.info(result.getToken() + "=======================================token");
// 5-断言结果
assertThat(bodyJson.get("code"),equalTo(0));
}
}
第二部分 基本类
RequestBuilder
格式基本固定
不同的请求需要对第二步进行更改,也就是搭建请求数据
① RequestMapping
属于GET请求
- 无参
RequestBuilder builder = MockMvcRequestBuilders
.get(url)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
- 有参(非路径)
// 要用这个map
// 注意添加方法为add put只能添加List
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("type", "3");
params.add("page", "1");
params.add("limit", "2");
RequestBuilder builder = MockMvcRequestBuilders
.get(url)
.params(params)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
- 有参(路径参数)
// url = /certificate/certificateInfo/getCertificateWithoutPic/{page}/{limit}/{type}
RequestBuilder builder = MockMvcRequestBuilders
.get(url,value1,value2,value3)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
② PostMapping
属于post请求
- 有参(@RequestBody)
// 要传入Json对象的字符串形式,所以一般会把参数对象先转成JSON对象
JSONObject jsonObject = JSONObject.fromObject(param);
RequestBuilder builder = MockMvcRequestBuilders
.post(url)
.content(jsonObject.toString())
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
- 有参(@PathVariable)
RequestBuilder builder = MockMvcRequestBuilders
.post(url,value1)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
③ GetMapping
属于GET请求
与RequestMapping一致
④ DeleteMapping
request = delete("/api/v1/folders/参数");
第三部分 集成shiro
集成 shiro之后每次使用测试都需要登陆验证
1. 实现shiro的登陆验证
在这里定义权限,穿过这些东西
package com.internetCafes.base;
import com.internetCafes.entity.login.LoginReq;
import com.internetCafes.entity.login.LoginRes;
import com.internetCafes.spms.ApplicationBootstrap;
import com.internetCafes.spms.web.sys.oauth2.OAuth2Token;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.subject.WebSubject;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import javax.annotation.Resource;
/**
* 单元测试基本类
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationBootstrap.class)
@WebAppConfiguration
public abstract class ApiBaseControllerTest extends BaseTest {
// 日志
protected static Logger logger = LoggerFactory.getLogger(ApiBaseControllerTest.class);
// webAppliactionContext
@Autowired
protected WebApplicationContext webApplicationContext;
// shiro的Manger
@Resource
private org.apache.shiro.mgt.SecurityManager securityManager;
// 单元测试核心
protected MockMvc mvc;
// 权限
private Subject subject;
protected static String token = null;//token
private MockHttpServletRequest mockHttpServletRequest;
private MockHttpServletResponse mockHttpServletResponse;
/**
* 初始化方法,执行当前测试类的每个测试方法前执行
* 初始化mvc,获取token等
*/
@Before
public void setUp() {
System.out.println("controller test is starting");
mockHttpServletRequest = new MockHttpServletRequest(webApplicationContext.getServletContext());
mockHttpServletResponse = new MockHttpServletResponse();
MockHttpSession mockHttpSession = new MockHttpSession(webApplicationContext.getServletContext());
mockHttpServletRequest.setSession(mockHttpSession);
SecurityUtils.setSecurityManager(securityManager);
mvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.build();
subject = new WebSubject.Builder(mockHttpServletRequest, mockHttpServletResponse)
.buildWebSubject();
// 登录获取token
if (token == null) {
System.out.println("token");
token = login();
}
OAuth2Token oAuth2Token = new OAuth2Token(token);
subject.login(oAuth2Token);
ThreadContext.bind(subject);
}
/**
* 释放资源,执行当前测试类的每个测试方法后执行
*/
@After
public void tearDown() {
System.out.println("controller test is over");
}
/**
* 登录方法
* <p>
* 仅用于开发环境单元测试
* 因为仅在开发环境中验证码密码等关闭
* </p>
*/
protected String login() {
subject = new WebSubject.Builder(mockHttpServletRequest, mockHttpServletResponse)
.buildWebSubject();
// 1-请求数据,自己的请求接口
String url = "/sys/login";
LoginReq loginReq = new LoginReq("杨河测试账号", "13037617240", "123456", "captcha", "uuid");
JSONObject content = JSONObject.fromObject(loginReq);
// 2-构造请求
RequestBuilder postBuilder = getPostBuilder(url, content);
//执行请求
try {
// 3-执行请求-及判断请求结果
MvcResult mvcResult = performMVC(mvc, postBuilder);
// 4-处理返回参数,获取token
String contentAsString = mvcResult.getResponse().getContentAsString();
JSONObject jsonObject = JSONObject.fromObject(contentAsString);
// 5-结果值封装
LoginRes result = (LoginRes) JSONObject.toBean(jsonObject, LoginRes.class);
if (result == null) {
return "";
}
logger.info("token获取成功:" + result.getToken());
return result.getToken();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
2. 封装RequsetBuilder
对构建 RequsetBuilder 进行抽取整合,简便后来的操作
package com.internetCafes.base;
import net.sf.json.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.util.MultiValueMap;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* 请求部分操作逻辑内容封装
*/
public abstract class BaseTest {
/**
* 构建 Post请求 无token
*
* @param url 请求地址
* @param jsonObject 请求参数
* @author Zj
*/
protected static RequestBuilder getPostBuilder(String url, JSONObject jsonObject){
RequestBuilder builder = MockMvcRequestBuilders
.post(url)
.content(jsonObject.toString())
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
return builder;
}
/**
* 构建 Post请求 带token
*
* @param url 请求地址
* @param jsonObject 请求参数
* @author Zj
*/
protected static RequestBuilder getPostBuilder(String url, JSONObject jsonObject,String token){
RequestBuilder builder = MockMvcRequestBuilders
.post(url)
.header("token",token)
.content(jsonObject.toString())
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
return builder;
}
/**
* 构建 Get请求 不带token
*
* @param url 请求地址
* @param params 请求参数
* @author Zj
*/
protected RequestBuilder getGetBuilder(String url, MultiValueMap<String,String> params){
RequestBuilder builder = MockMvcRequestBuilders
.get(url)
.params(params)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
return builder;
}
/**
* 构建 Get请求 带token 无参数
*
* @param url 请求地址
* @param token 用户token
* @author Zj
*/
protected RequestBuilder getGetBuilder(String url, String token){
RequestBuilder builder = MockMvcRequestBuilders
.get(url)
.header("token",token)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
return builder;
}
/**
* 构建 Get请求 带token 带参数
*
* @param url 请求地址
* @param token 用户token
* @author Zj
*/
protected RequestBuilder getGetBuilder(String url, MultiValueMap<String,String> params,String token){
RequestBuilder builder = MockMvcRequestBuilders
.get(url)
.header("token",token)
.params(params)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
return builder;
}
/**
* 请求执行,获取请求结果
* @param mvc
* @param builder
* @author Zj
*/
protected MvcResult performMVC(MockMvc mvc, RequestBuilder builder){
try {
MvcResult mvcResult = mvc.perform(builder)
.andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk())
/*.andExpect(jsonPath("code").value(1))注释,因为该项目中每个接口的数据格式没有统一,不能够用code判断*/
.andReturn();
return mvcResult;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
3. 基本测试类
继承基本测试类
public class EntCustomerCooperationControllerTest extends ApiBaseControllerTest {
/**
* POST请求
* /ent/customer/cooperation/paging
* 客户合作记录分页
*/
@Test
public void paging() throws UnsupportedEncodingException {
// 设置url
String url = "/ent/customer/cooperation/paging";
// 定义请求参数
PageItemDTO<CustomerCooperationPagingTDO> pageItemDTO = new PageItemDTO<>();
CustomerCooperationPagingTDO customerCooperationPagingDTO = new CustomerCooperationPagingTDO();
customerCooperationPagingDTO.setCustomerId(23L);
pageItemDTO.setConditions(customerCooperationPagingDTO);
// 使用我们封装的方法进行便捷测试
MvcResult mvcResult = performMVC(mvc, getPostBuilder(url, JSONObject.fromObject(pageItemDTO)));
// 对返回值进行封装
JSONObject bodyJson = JSONObject.fromObject(mvcResult.getResponse().getContentAsString());
logger.info(bodyJson.toString());
// 断言
assertThat(bodyJson.get("code"),equalTo(0));
}
}
第四部分 模板(含shiro)
1. 封装RequsetBuilder
所有单元测试的基础类,用于封装一些通用的请求方式
比如:POST请求、PUT请求等
package com.internetCafes.base;
import com.internetCafes.spms.core.exception.RRException;
import net.sf.json.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.util.MultiValueMap;
import java.util.ArrayList;
import java.util.Arrays;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* 请求部分操作逻辑内容封装
*/
public abstract class BaseTest {
/**
* 通过bodyJson 也就是接口返回值的body部分 获取指定key的value
*
* @param bodyJson 接口返回值的body部分
* @param key 指定参数
* @return value
* @author llz
*/
protected String getValueFromBodyJsonByKey(JSONObject bodyJson, String key) {
String[] values = bodyJson.get("data").toString().split("\"");
ArrayList<String> valueList = new ArrayList<>(Arrays.asList(values));
int index = valueList.indexOf(key);
String value;
// 对不同类型的唯一值进行分别处理
if (key.toLowerCase().contains("id")) {
value = valueList.get(index + 1);
return value.substring(1,value.length()-1);
} else {
return valueList.get(index + 2);
}
}
/**
* 构建上传文件的POST请求
*
* @param url 路径
* @param file 文件
* @return 返回值
* @author llz
*/
protected RequestBuilder getFilePostBuilder(String url, MockMultipartFile file) {
return MockMvcRequestBuilders
.multipart(url)
.file(file);
}
/**
* 唯一字段 存在判断
*
* @param jsonBody 结果数据
* @param uniqueKey 唯一字段名称
* @param uniqueValue 唯一字段值
* @author llz
*/
protected void isExistValue(String jsonBody, String uniqueKey, Object uniqueValue) {
String[] values = jsonBody.split("\"");
ArrayList<String> valueList = new ArrayList<>(Arrays.asList(values));
int index = valueList.indexOf(uniqueKey);
try {
// 对不同类型的唯一值进行分别处理
if (uniqueValue.getClass().getSimpleName().equals("Long")) {
String value = valueList.get(index + 1);
assertThat(value, equalTo(":" + uniqueValue + ","));
} else {
String value = valueList.get(index + 2);
assertThat(value, equalTo(uniqueValue));
}
} catch (Exception e) {
throw new RRException(e.getMessage() + "-----------测试失败");
}
}
/**
* 构建 PUT请求
*
* @param url 请求地址
* @param jsonObject 请求参数
* @author llz
*/
protected RequestBuilder getPutBuilder(String url, JSONObject jsonObject) {
return MockMvcRequestBuilders
.put(url)
.content(jsonObject.toString())
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
}
/**
* 构建 Post请求 无token
*
* @param url 请求地址
* @param jsonObject 请求参数
* @author Zj
*/
protected RequestBuilder getPostBuilder(String url, JSONObject jsonObject) {
return MockMvcRequestBuilders
.post(url)
.content(jsonObject.toString())
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
}
/**
* 封装结果断言 如果存在 500 代码 或者存在 ”未知异常,请联系管理员“ 都视为失败
*
* @author llz
*/
protected void assertCodeAndMsg(JSONObject bodyJson, int code) {
assertThat(bodyJson.get("code"), equalTo(code));
if (bodyJson.toString().contains("\"msg\":\"未知异常,请联系管理员")) {
throw new AssertionError("未知异常,请联系管理员");
}
}
/**
* 构建 Post请求 带token
*
* @param url 请求地址
* @param jsonObject 请求参数
* @author Zj
*/
protected static RequestBuilder getPostBuilder(String url, JSONObject jsonObject, String token) {
return MockMvcRequestBuilders
.post(url)
.header("token", token)
.content(jsonObject.toString())
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
}
/**
* 构建 Get请求 不带token
*
* @param url 请求地址
* @param params 请求参数
* @author Zj
*/
protected RequestBuilder getGetBuilder(String url, MultiValueMap<String, String> params) {
return MockMvcRequestBuilders
.get(url)
.params(params)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
}
/**
* 构建 Get请求 带token 无参数
*
* @param url 请求地址
* @param token 用户token
* @author Zj
*/
protected RequestBuilder getGetBuilder(String url, String token) {
return MockMvcRequestBuilders
.get(url)
.header("token", token)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
}
/**
* 构建 Get请求 带token 带参数
*
* @param url 请求地址
* @param token 用户token
* @author Zj
*/
protected RequestBuilder getGetBuilder(String url, MultiValueMap<String, String> params, String token) {
return MockMvcRequestBuilders
.get(url)
.header("token", token)
.params(params)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
}
/**
* 请求执行,获取请求结果
*
* @param mvc mvc
* @param builder builder
* @author Zj
*/
protected MvcResult performMVC(MockMvc mvc, RequestBuilder builder) {
long startTime = 0L;
long endTime;
try {
startTime = System.currentTimeMillis();
return mvc.perform(builder)
// .andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk())
/*.andExpect(jsonPath("code").value(1))注释,因为该项目中每个接口的数据格式没有统一,不能够用code判断*/
.andReturn();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
endTime = System.currentTimeMillis();
System.out.println("接口运行耗费时间为:" + (endTime - startTime) + " ms");
}
}
}
2. 基础Controller
ApiBaseControllerTest
在这一步把shiro登陆验证实现
主要作用:实现用户模拟登录、初始化单元测试需要的实体类(MockHttpServletRequest)
package com.internetCafes.base;
import com.internetCafes.entity.login.LoginReq;
import com.internetCafes.entity.login.LoginRes;
import com.internetCafes.spms.ApplicationBootstrap;
import com.internetCafes.spms.web.sys.oauth2.OAuth2Token;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.subject.WebSubject;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import javax.annotation.Resource;
/**
* 单元测试基本类
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationBootstrap.class)
@WebAppConfiguration
public abstract class ApiBaseControllerTest extends BaseTest {
protected static Logger logger = LoggerFactory.getLogger(ApiBaseControllerTest.class);
@Autowired
protected WebApplicationContext webApplicationContext;
@Resource
private org.apache.shiro.mgt.SecurityManager securityManager;
protected MockMvc mvc;
private Subject subject;
protected static String token = null;//token
private MockHttpServletRequest mockHttpServletRequest;
private MockHttpServletResponse mockHttpServletResponse;
/**
* 初始化方法,执行当前测试类的每个测试方法前执行
*/
@Before
public void setUp() {
System.out.println("controller test is starting");
mockHttpServletRequest = new MockHttpServletRequest(webApplicationContext.getServletContext());
mockHttpServletResponse = new MockHttpServletResponse();
MockHttpSession mockHttpSession = new MockHttpSession(webApplicationContext.getServletContext());
mockHttpServletRequest.setSession(mockHttpSession);
SecurityUtils.setSecurityManager(securityManager);
mvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.build();
subject = new WebSubject.Builder(mockHttpServletRequest, mockHttpServletResponse)
.buildWebSubject();
/*mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();*/
if (token == null) {
System.out.println("token");
token = login();
}
OAuth2Token oAuth2Token = new OAuth2Token(token);
subject.login(oAuth2Token);
ThreadContext.bind(subject);
/*if (token == null) {
System.out.println("token");
token = login();
}
mockHttpServletRequest = new MockHttpServletRequest(webApplicationContext.getServletContext());
mockHttpServletResponse = new MockHttpServletResponse();
MockHttpSession mockHttpSession = new MockHttpSession(webApplicationContext.getServletContext());
mockHttpServletRequest.setSession(mockHttpSession);
SecurityUtils.setSecurityManager( securityManager);*/
/*SecurityUtils.setSecurityManager(webApplicationContext.getBean(""));*/
/*SecurityUtils.setSecurityManager(securityManager);*/
}
/**
* 释放资源,执行当前测试类的每个测试方法后执行
*/
@After
public void tearDown() {
System.out.println("controller test is over");
}
/**
* 登录方法
* <p>
* 仅用于开发环境单元测试
* 因为仅在开发环境中验证码密码等关闭
* </p>
*
* @author Zj
*/
protected String login() {
subject = new WebSubject.Builder(mockHttpServletRequest, mockHttpServletResponse)
.buildWebSubject();
// 1-请求数据
String url = "/sys/login";
LoginReq loginReq = new LoginReq("系统管理", "admin", "123456", "captcha", "uuid");
JSONObject content = JSONObject.fromObject(loginReq);
// 2-构造请求
RequestBuilder postBuilder = getPostBuilder(url, content);
//执行请求
try {
// 3-执行请求-及判断请求结果
MvcResult mvcResult = performMVC(mvc, postBuilder);
// 4-处理返回参数,获取token
String contentAsString = mvcResult.getResponse().getContentAsString();
JSONObject jsonObject = JSONObject.fromObject(contentAsString);
// 5-结果值封装
LoginRes result = (LoginRes) JSONObject.toBean(jsonObject, LoginRes.class);
if (result == null) {
return "";
}
logger.info("token获取成功:" + result.getToken());
return result.getToken();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
3. 分页请求参数封装
PageItemDTOTest<T>
封装分页请求数据,一般用于分页接口请求
package com.internetCafes.base;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.Valid;
/**
* 分页请求参数
*/
@ApiModel
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageItemDTOTest<T> {
@ApiModelProperty(value = "当前页数", required = true)
private Integer pageNum = 1;
@ApiModelProperty(value = "单页条数", required = true)
private Integer pageSize = 2;
@ApiModelProperty(value = "需要排序字段", required = true)
private String orderBy;
@ApiModelProperty(value = "asc正序 desc倒序", required = true)
private String inOrder;
@Valid
@ApiModelProperty(value = "检索条件")
private T conditions;
}