RestFul黄瓜验收测试以获取本地文件json作为输出

时间:2016-03-30 13:30:11

标签: json rest restful-url resttemplate

我想模拟一个resttemplate输出。我们有一个服务 / someservice / getJson 来获取json。为了模拟这个服务,我们在代码库中保存了一个json文件,并尝试按如下方式将它送到响应实体。

工作代码:

String baseURL = "http://localhost:1010"
String uri = /someservice/getJson
ResponseEntity<T> entity = restTemplate.exchange(baseURL + uri, GET, new HttpEntity<>(headers), type);

我在代码库中有一个json文件(比如codebase /../ resource / myfile.json) 我想把响应实体作为本地json我模拟。 我尝试过使用交换方法。它似乎并不适合我。

我用json文件尝试了什么

String localJson = "/resource/myfile.json";
ResponseEntity<T> entity = restTemplate.exchange(localJson, GET, new HttpEntity<>(headers), type);

我认为除了 exchange 之外还有其他方法可以完成它。但我不知道那些。 在我尝试的内容中是否还有其他方式/错误?

1 个答案:

答案 0 :(得分:0)

要使用JSON对象读取文件并将其转换为POJO,您可以使用ObjectMapper 来自readValue(File src, Class<T> valueType)框架的Jackson方法(readValue doc link):

import java.io.File;
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();
YourJsonType response = mapper.readValue( new File("file with JSON object")  , YourJsonType.class);