4

I have a simple class for storing values in the cache, similar to this:

public class PersonSessionCache {

    private static final String PERSON_KEY = 'Person';

    public static Id getPersonId(){

        if (Cache.Session.contains(PERSON_KEY)){
            return (Id)Cache.Session.get(PERSON_KEY);    
        }
        return null;
    }

    public static void setPersonId(Id personId){
        Cache.Session.put(PERSON_KEY, personId)
    }

    public static void clearCache(){
        Cache.Session.remove(PERSON_KEY);
    }
}

But I get this error message when I run my unit test:

cache.Session.SessionCacheException: A default partition was not found. To cache without partition reference, designate a partition as default.

QUESTIONS

  • What do I need to do to designate a partition as default?
  • What would I need to change in the code to make it work with the partition?
  • Is it possible/should I unit test the Cache?
6

What do I need to do to designate a partition as default?

Check the "Default Partition" checkbox on the partition to make it the default partition. This is the first checkbox on the Platform Cache Partition Edit page.


What would I need to change in the code to make it work with the partition?

If you have a default set, no need to do anything. Otherwise, call getPartition:

Cache.SessionPartition partition = Cache.Session.getPartition('partitionname');
...
if(partition.contains(getPersonCacheKey()) {
  return (Id)partition.get(getPersonCacheKey());
}
...

Is it possible/should I unit test the Cache?

There's no need to unit test system libraries. For example, would you write the following unit test?

@isTest static void makeSureSystemWorks() {
  System.assertEquals(2, 1 + 1);
  System.assertEquals(4, 2 * 2);
  ...

Of course not. Salesforce already has unit tests that makes sure that Salesforce is working correctly. You don't need to verify that the cache is correctly storing data, because it is. Your code, however, needs to be aware that caches can be invalidated at any time and account for that possibility.

2
  • Thanks. My last question wasn't very good, I really meant to find out if it was able to test the cache or if I had to Mock it. But my test coverage works now. – Robs Jul 24 '18 at 7:34
  • 1
    @Robs Oh, that makes a bit more sense. But as you've discovered, cache does work with unit tests. – sfdcfox Jul 24 '18 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.