存储 object 供以后在 java 中使用
Store object for later use in java
我正在使用 Rest assured API 测试自动化。我想在调用 API 后将 Response 存储为 object,这样我就可以使用 object 来验证一些数据,比如状态码、body、header和所有。
我尝试使用 System.setPropery
但它只允许存储字符串,如果将响应存储为字符串,如 System.setProperty("test", response.toString());
并尝试检索 System.getProperty("test");
然后抛出错误
java.lang.ClassCastException: java.lang.String cannot be cast to
io.restassured.response.Response
有没有办法在某处存储 object 并访问它供以后使用?
不要将 System.Properties
用于此目的。
请使用下面给出的简单缓存存储。
public class ResponseCache {
private static final ResponseCache myInstance = new ResponseCache();
private final Map<String, Response> cacheStore = new HashMap<>();
private ResponseCache() {
}
public static ResponseCache getInstance() {
return myInstance;
}
public void addResponse(String key, Response value) {
cacheStore.put(key, value);
}
public boolean exists(String key) {
return cacheStore.containsKey(key);
}
public void remove(String key) {
if (exists(key)) {
cacheStore.remove(key);
}
}
public Response get(String key) {
return exists(key) ? cacheStore.get(key) : null;
}
}
执行工作完成后,您可以删除该密钥。
我正在使用 Rest assured API 测试自动化。我想在调用 API 后将 Response 存储为 object,这样我就可以使用 object 来验证一些数据,比如状态码、body、header和所有。
我尝试使用 System.setPropery
但它只允许存储字符串,如果将响应存储为字符串,如 System.setProperty("test", response.toString());
并尝试检索 System.getProperty("test");
然后抛出错误
java.lang.ClassCastException: java.lang.String cannot be cast to io.restassured.response.Response
有没有办法在某处存储 object 并访问它供以后使用?
不要将 System.Properties
用于此目的。
请使用下面给出的简单缓存存储。
public class ResponseCache {
private static final ResponseCache myInstance = new ResponseCache();
private final Map<String, Response> cacheStore = new HashMap<>();
private ResponseCache() {
}
public static ResponseCache getInstance() {
return myInstance;
}
public void addResponse(String key, Response value) {
cacheStore.put(key, value);
}
public boolean exists(String key) {
return cacheStore.containsKey(key);
}
public void remove(String key) {
if (exists(key)) {
cacheStore.remove(key);
}
}
public Response get(String key) {
return exists(key) ? cacheStore.get(key) : null;
}
}
执行工作完成后,您可以删除该密钥。