Java 如何测试从不断变化的外部API中获取价值的RESTAPI端点
我使用外部API,它返回按日期排序的对象列表,其中包含许多(大约30个)属性 我使用一个端点的SpringBoot编写了简单的RESTAPIJava 如何测试从不断变化的外部API中获取价值的RESTAPI端点,java,unit-testing,spring-boot,testing,integration-testing,Java,Unit Testing,Spring Boot,Testing,Integration Testing,我使用外部API,它返回按日期排序的对象列表,其中包含许多(大约30个)属性 我使用一个端点的SpringBoot编写了简单的RESTAPI /newst\u obj\u name 它只返回该列表中当前最新的对象名称,而忽略其他所有内容 当外部API的值不断变化时,如何充分测试该代码,因此我不能像下面的代码那样简单地使用String expected 一般来说,在那个场景中如何处理整个测试问题 @RunWith(SpringRunner.class) @SpringBootTest(classe
/newst\u obj\u name
它只返回该列表中当前最新的对象名称,而忽略其他所有内容
当外部API的值不断变化时,如何充分测试该代码,因此我不能像下面的代码那样简单地使用String expected
一般来说,在那个场景中如何处理整个测试问题
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyTest {
@LocalServerPort
private int port;
private TestRestTemplate restTemplate = new TestRestTemplate();
private HttpHeaders headers = new HttpHeaders();
@Test
public void testRetrieveNewest() {
HttpEntity<String> entity = new HttpEntity<String>(null, headers);
ResponseEntity<String> response = restTemplate.exchange(
createURLWithPort("/newest_obj_name"),
HttpMethod.GET, entity, String.class);
String expected = "{\"name\":\"crazy\"}";
try {
JSONAssert.assertEquals(expected, response.getBody(), false);
} catch (JSONException e) {
e.printStackTrace();
}
}
private String createURLWithPort(String uri) {
return "http://localhost:" + port + uri;
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(class=Application.class,webEnvironment=SpringBootTest.webEnvironment.RANDOM\u端口)
公共类MyTest{
@本地服务器端口
专用int端口;
私有TestRestTemplate restTemplate=新TestRestTemplate();
私有HttpHeaders=新HttpHeaders();
@试验
公共void testRetrieveNewest(){
HttpEntity=新的HttpEntity(空,标题);
ResponseEntity response=restemplate.exchange(
createURLWithPort(“/newst_obj_name”),
HttpMethod.GET、实体、字符串.class);
应为字符串=“{\'name\”:\'crazy\”;
试一试{
assertEquals(应为response.getBody(),false);
}捕获(JSONException e){
e、 printStackTrace();
}
}
私有字符串createURLWithPort(字符串uri){
返回“http://localhost:“+端口+uri;
}
}
编写一个模拟外部API的单元测试,并测试您的逻辑是否正确。在这个集成测试中,只需检查响应是否具有预期的结构,而不测试实际值。您能提供一些代码片段吗?因为为了提取字符串名,我需要在我的服务中转换ResponseEntity。因此,如果我在编写单元测试时没有错的话,我将使用完全相同的代码测试我的服务中的代码,以动态转换来自外部API的响应?编写一个模拟外部API的单元测试,并测试您的逻辑是否正确。在这个集成测试中,只需检查响应是否具有预期的结构,而不测试实际值。您能提供一些代码片段吗?因为为了提取字符串名,我需要在我的服务中转换ResponseEntity。所以,如果我在编写单元测试时没有弄错的话,我将使用完全相同的代码来测试我的服务中的代码,以便动态地转换来自外部API的响应?