RestTemplate是Spring提供的用于访问Rest服务的,RestTemplate提供了多种便捷访问远程Http服务的方法,传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient。不过此种方法使用起来太过繁琐。spring提供了一种简单便捷的模板类来进行操作,这就是RestTemplate。
// 声明了RestTemplate
private final RestTemplate restTemplate;
// 当bean 没有无参构造函数的时候,spring将自动拿到有参的构造函数,参数进行自动注入
public OrderController(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
}
@RequestMapping("/order")
public String order(){
// 下单 需要远程访问rest服务
// 基于restTemplate 调用查询
Result forObject = restTemplate.getForObject("http://localhost:8080/user/{id}", Result.class, 1);
return forObject.toString();
// 基于restTemplate 调用新增 }2.通过mockmvc测试
@SpringBootTest
@AutoConfigureMockMvc //专门用于做mockmvc的, 由spring-test提供, 依赖junit5, 如果没有该注解需要通过代码构建MockMvc
public class MockMvcTests {
@Autowired
MockMvc mockMvc;
@Test
void testMockMVCGet() throws Exception {
// 发起一个模拟请求 ,不依赖网络,不依赖web服务, 不需要启动web应用
mockMvc.perform(
MockMvcRequestBuilders.get("/user/{id}", 1) // 发送了get请求
.accept(MediaType.APPLICATION_JSON_UTF8) // 设置响应的文本类型
//.param(name,value) ?name=xx&age=xx
)
// 响应断言
.andExpect(MockMvcResultMatchers.status().isOk()) // 断言状态码为200
.andExpect(MockMvcResultMatchers.jsonPath("$.data.username").value("zhangsanxx"))
.andDo(MockMvcResultHandlers.print());
}
@Test
void testMockMVCPost() throws Exception {
String userJson = "{n" +
" "username": "yang",n" +
" "address": "mockMVC",n" +
" "birthday": "2020/01/01"n" +
"}";
System.out.println(userJson);
// 发起一个模拟请求 ,不依赖网络,不依赖web服务, 不需要启动web应用
mockMvc.perform(
MockMvcRequestBuilders.post("/user/add") // 发送了get请求
.accept(MediaType.APPLICATION_JSON_UTF8) // 设置响应的文本类型
.contentType(MediaType.APPLICATION_JSON_UTF8) // 设置请求的文本类型
.content(userJson) // json数据
//.param(name,value) ?name=xx&age=xx
)
// 响应断言
.andExpect(MockMvcResultMatchers.status().isOk()) // 断言状态码为200
//.andExpect(MockMvcResultMatchers.jsonPath("$.data.length()").value(5))
.andDo(MockMvcResultHandlers.print());
}
}



