契约测试主要思想是把接口之间的调用关系解耦, 即一个应用在本地模拟对另一个应用的接口的调用,把对接口的测试转化为本地的单元测试。
场景:Consumer服务需要调用Provider服务的人员信息查询接口,Consumer端在进行测试的时候就可以采用契约测试
1、Provider端定义契约文件,测试基类,运行插件生成相应的stubs.jar
Contract.make {
description "should return one user success"
request {
method 'GET'
urlPath('/user/1')
}
response {
status 200
body('''{
"id": "1",
"name": "Jack",
"age": 22,
"phone": "6659852"
}''')
headers {
header('Content-Type', 'application/json;charset=UTF-8')
}
}
}
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMessageVerifier
@DirtiesContext
@AutoConfigureMockMvc
public class ProviderApplicationTests {
@Autowired
private WebApplicationContext context;
@Before
public void setUp() {
RestAssuredMockMvc.webAppContextSetup(context);
}
}
2、Consumer端获取stubs.jar,在Provider端不启动的情况下,进行接口调用。
public class UserValidateController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/query")
public ResponseDto queryUserInfo(@RequestParam String id){
User user = restTemplate.getForObject("http://localhost:8080/user/"+id,User.class);
if(user==null){
return new ResponseDto(false,"人员信息不存在","");
}else{
System.out.println("调用Provider服务getOneUser接口返回的数据: "+ user.toString());
return new ResponseDto(true,"查询成功",user);
}
}
}
具体流程参考:契约测试指引
网友评论