7

When writing Apex test cases for code that utilizes the platform cache what are the important scenarios I need to cover?

Additionally, how would I address those is the test methods?

For instance, can you adapt the test cases based on the partitions capacity.

9

The first and most obvious scenario is the handling of a cache miss and hit. It appears that the local cache in testing context is isolated. So it will always start out empty. The exact method of testing will depend on implementation, but generally you could either:

  1. call the same code twice in succession to first miss and populate the cache. Then subsequently hit the cache. Ideally assertions would be made that the results are the same and that the cached result was faster (as measured via elapsed time).
  2. Use two independent test methods. One that asserts the expected the result when the cache misses. The other that explicitly inserts into the cache before calling the method so a hit will occur.

Assertions can be made via getMissRate() about the expected outcome.

Other scenarios to consider:

  1. Is the code optimized to retrieve multiple keys from the cache in one call. Ref. Group Cache Requests
  2. Does the code correctly handle hitting the Cache Partition Size Limit.
  3. Does the code correctly handle attempts to cache items that exceed the Local Cache Size Limit.
  4. Does the code correctly handle attempts to cache items that exceed the Single Cached Item Size limit. Will be thrown as a Cache.ItemSizeLimitExceededException exception. See getMaxValueSize()
  5. Will all items generate valid alphanumeric cache keys. See validateKey() and similar methods.
  6. What happens if there is no capacity allocated to the partition - How can I detect that a packaged Platform Cache Partition has no capacity allocated?
| improve this answer | |
  • I'm going to try and evolve this answer as I work through it. Contributions or independent answers welcomed. For instance, there will be a number of special considerations around Session partitions that I haven't covered. – Daniel Ballinger Feb 19 '18 at 21:27

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.