spring boot使用TestRestTemplate集成测试 RESTful 接口
只是单纯的记录一下如何用TestRestTemplate访问受security保护的api,供以后查阅。
-
-
-
-
public class AccountControllerTests {
-
-
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);
-
}
-
-
-
public void testAccount() throws Exception {
-
login();
-
getUserInfo();
-
logout();
-
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
2019-04-01 测试管理平台大比拼