function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Krizia BuckKrizia Buck 

How do you test your use of Platform Cache in a test class?

For simplicity, one method in my class looks a little like this and it works in manual testing: 
@AuraEnabled
    public static String getCitySuggestions(String input) {
        String response;
        String url = GOOGLE_PLACE_AUTOCOMPLETE_ENDPOINT + 'input=' + EncodingUtil.urlEncode(input, 'UTF-8') + '&types=(cities)' + getKey();
        String key = input.replaceAll('[^a-zA-Z0-9]', '');
        //Input will sometimes include a '.' or space, cannot cache
        if ((key == input) && (key.length() <= 50)) {
            if (!Cache.Org.contains(key)) {
                response = getResponse(url);
                Cache.Org.put(key, response);
            } else {
                response = (String) Cache.Org.get(key);
            }
            if (!response.contains('"status" : "OK"')) {
                Cache.Org.remove(key);
            }
        } else {
            response = getResponse(url);
        }
        return response;
    }
In my test class, I run the same method twice so that I should hit the lines that populate the cache the first time then the lines that access the cache in the second. Only the lines that populate the cache run and if I have an assert to make sure the cache has the value, it fails. 

How do I test Platform Cache in a test class? 
 
Divyesh DudhatDivyesh Dudhat
if (!Cache.Org.contains(key)) {
                response = getResponse(url);
                Cache.Org.put(key, response);
            } else {
                response = (String) Cache.Org.get(key);
  }


In this code,

if key is available then 'if (!Cache.Org.contains(key))' condition return false and you're going to get key who really never contains by the Cache.Org..

Please check your logic one and after create a test class.

about test class.

once i put some cache in Cache.Org then hit that code once again by calling same function then i'll get that cache there.

thanks.