Search code examples
javarest-assured

Store object for later use in java


I'm working on API testing automation using Rest assured. I would like to store Response as an object after calling an API so I can validate some data using that object like, status code, body, header and all.

I tried using System.setPropery but it allows to store only String and if store Response as String like System.setProperty("test", response.toString()); and try to retrieve System.getProperty("test"); then throws the error

java.lang.ClassCastException: java.lang.String cannot be cast to io.restassured.response.Response

It there a way to store an object somewhere and access it for later use?


Solution

  • Don't use System.Properties for this purpose. Please use a simple cache store as given below.

    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;
        }
    
    }
    

    Once your execution work is completed you can remove that key.