![](/img/trans.png)
[英]Java: How to store entire object to an external location and reuse it to recreate the object for later use?
[英]Store object for later use in java
我正在使用放心的 API 測試自動化。 我想在調用 API 后將 Response 存儲為一個對象,以便我可以使用該對象驗證一些數據,例如狀態代碼、正文、標題等。
我嘗試使用System.setPropery
但它只允許存儲 String 並且如果將 Response 存儲為 String 就像System.setProperty("test", response.toString());
並嘗試檢索System.getProperty("test");
然后拋出錯誤
java.lang.ClassCastException: java.lang.String 不能轉換為 io.restassured.response.Response
有沒有辦法將對象存儲在某處並訪問它以備后用?
不要為此目的使用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;
}
}
執行工作完成后,您可以刪除該密鑰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.