这篇文章没什么技术含量,只是单纯的记录一下如何用TestRestTemplate访问受security保护的api,供以后查阅。

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class AccountControllerTests {
@Autowired
private TestRestTemplate restTemplate;
private HttpEntity httpEntity; /**
* 登录
* @throws Exception
*/
private void login() throws Exception {
String expectStr = "{\"code\":0,\"msg\":\"success\"}";
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("username", "183xxxxxxxx");
map.add("password", "123456");
ResponseEntity responseEntity = restTemplate.postForEntity("/api/account/sign_in", map, String.class);
//添加cookie以保持状态
HttpHeaders headers = new HttpHeaders();
String headerValue = responseEntity.getHeaders().get("Set-Cookie").toString().replace("[", "");
headerValue = headerValue.replace("]", "");
headers.set("Cookie", headerValue);
httpEntity = new HttpEntity(headers);
assertThat(responseEntity.getBody()).isEqualTo(expectStr);
} /**
* 登出
* @throws Exception
*/
private void logout() throws Exception {
String expectStr = "{\"code\":0,\"msg\":\"success\"}";
String result = restTemplate.postForObject("/api/account/sign_out", null, String.class, httpEntity);
httpEntity = null;
assertThat(result).isEqualTo(expectStr);
} /**
* 获取信息
* @throws Exception
*/
private void getUserInfo() throws Exception {
Detail detail = new Detail();
detail.setNickname("疯狂的米老鼠");
detail.setNicknamePinyin("fengkuangdemilaoshu");
detail.setSex(1);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
detail.setCreatedAt(sdf.parse("2017-11-03 16:43:27"));
detail.setUpdatedAt(sdf.parse("2017-11-03 16:43:27"));
Role role = new Role();
role.setName("ROLE_USER_NORMAL");
Set<Role> roles = new HashSet<>();
roles.add(role);
User user = new User();
user.setId(1L);
user.setPhone("183xxxxxxxx");
user.setEmail("xxxxxx@gmail.com");
user.setDetail(detail);
user.setRoles(roles);
ResultBean<User> resultBean = new ResultBean<>();
resultBean.setData(user);
ObjectMapper om = new ObjectMapper();
String expectStr = om.writeValueAsString(resultBean);
ResponseEntity<String> responseEntity = restTemplate.exchange("/api/user/get_user_info", HttpMethod.GET, httpEntity, String.class);
assertThat(responseEntity.getBody()).isEqualTo(expectStr);
} @Test
public void testAccount() throws Exception {
login();
getUserInfo();
logout();
}

  

spring boot使用TestRestTemplate集成测试 RESTful 接口的更多相关文章

  1. Spring Boot 集成 Swagger 生成 RESTful API 文档

    原文链接: Spring Boot 集成 Swagger 生成 RESTful API 文档 简介 Swagger 官网是这么描述它的:The Best APIs are Built with Swa ...

  2. Spring Boot的数据访问:CrudRepository接口的使用

    示例 使用CrudRepository接口访问数据 创建一个新的Maven项目,命名为crudrepositorytest.按照Maven项目的规范,在src/main/下新建一个名为resource ...

  3. Spring Boot启动过程及回调接口汇总

    Spring Boot启动过程及回调接口汇总 链接: https://www.itcodemonkey.com/article/1431.html 来自:chanjarster (Daniel Qia ...

  4. Spring Boot的TestRestTemplate使用

    文章目录 添加maven依赖 TestRestTemplate VS RestTemplate 使用Basic Auth Credentials 使用HttpClientOption 使用RestTe ...

  5. spring boot使用swagger生成api接口文档

    前言 在之前的文章中,使用mybatis-plus生成了对应的包,在此基础上,我们针对项目的api接口,添加swagger配置和注解,生成swagger接口文档 具体可以查看本站spring boot ...

  6. Spring Boot 2.x 编写 RESTful API (三) 程序层次 & 数据传输

    用Spring Boot编写RESTful API 学习笔记 程序的层次结构 相邻层级的数据传输 JavaBean 有一个 public 的无参构造方法 属性 private,且可以通过 get.se ...

  7. Spring Boot 2.x 编写 RESTful API (二) 校验

    用Spring Boot编写RESTful API 学习笔记 约束规则对子类依旧有效 groups 参数 每个约束用注解都有一个 groups 参数 可接收多个 class 类型 (必须是接口) 不声 ...

  8. 使用spring boot+mybatis+mysql 构建RESTful Service

    开发目标 开发两个RESTful Service Method Url Description GET /article/findAll POST /article/insert 主要使用到的技术 j ...

  9. Spring Boot 集成 Swagger,生成接口文档就这么简单!

    之前的文章介绍了<推荐一款接口 API 设计神器!>,今天栈长给大家介绍下如何与优秀的 Spring Boot 框架进行集成,简直不能太简单. 你所需具备的基础 告诉你,Spring Bo ...

随机推荐

  1. js自定义滚动样式

    <!DOCTYPE html> <html lang="en"> <head> <style type='text/css'> ht ...

  2. js,JQ获取短信验证码倒计时

    按钮 <a href="javasript:void(0);"onclick="settime(this);">获取手机验证码</a> ...

  3. Berlekamp-Massey算法简单介绍

    请阅读本文的同学们注意:之前这篇博客和所附代码有点问题,求的不一定是最短递推式,非常抱歉 看毛爷爷的论文大概断断续续看了一个月了,看得不是很懂,google了一波好像很快就看懂了,就先口胡一下这个算法 ...

  4. Python3爬虫知识点总结

    1.requests获取响应头的方法 eg:获取响应头信息 import requests res = request.head(url).headers print(res)

  5. 记Ubuntu Mongodb 和 Mysql的安装与使用

    安装mongodb 参考链接 https://www.cnblogs.com/shileima/p/7823434.html https://blog.csdn.net/xlengji/article ...

  6. day 51 js-2 函数,对象,正则 (定时器示例)

    本文转载自cnblogs.liwenzhou-----哪吒博客 先来一个定时器让我们看看函数的效果: <script src="/js/jquery-3.2.1.min.js" ...

  7. TF:Tensorflor之session会话的使用,定义两个矩阵,两种方法输出2个矩阵相乘的结果—Jason niu

    import tensorflow as tf matrix1 = tf.constant([[3, 20]]) matrix2 = tf.constant([[6], [100]]) product ...

  8. Codeforces 1095F Make It Connected 【MST】

    <题目链接> 题目大意: 给定一张n个顶点(每个顶点有点权)的无向图,并且给出边权为wi的m条边,顶点u和顶点v直接如果建边,边权为a_u + a_v,求图连通的最小边权和. 解题分析: ...

  9. 解决VS打开文件出现No EditorOptionDefinition export found for the given option name问题

    转载自http://stackoverflow.com/questions/23893497/no-editoroptiondefinition-export-found-error的第一个回答 Af ...

  10. 在Qt中调用Mupdf库进行pdf显示

    2018.5.10 更新内存对齐说明 感谢知乎网友@孤独子狮 指出QImage处需要考虑内存对齐的问题.因为本人缺乏跨平台.图形库开发经验,所以在调试成功后就没有深入探究. 主要修改了QImage的构 ...