Testing code using SoftReference <T>

In order for all code with SoftReference<T> be fully tested, you need to somehow test the case of "yup, it nulled". One could more or less mock this, using the "for test" code path to make the link be null, but it will not manage the queue in the same way as the GC does. I wonder if anyone can share their experience in creating a repeatable, controlled environment in which the GC is, in fact, provoked to collect and nullify.

+4
source share
2 answers

I would break the problem into two parts:

  • Checking the code path when returning null.
  • Testing SoftReference.

For # 1, I would use a Mock that returns null with enough change (sometimes null, sometimes a real object) to check all the relevant scripts that you think you will have with GC. This will be a unit test.

The next test is really an integration test to check how the behavior of the GC WRT SoftReference is as expected. I'm not sure that I will try to fully automate such a test, with the possible exception of the wider context of load testing, but if it is important, I would expand the JVM with a very tight maximum memory capacity and load enough memory to run a collection of software help. The failure path would be to prevent the code from using a soft link, loaded memory should throw an OutOfMemory error. Then run the tests by going to the soft link. The purpose of the tests should be to validate the assumptions made in unit tests of behavior.

+3
source

This answer explains how you can forcibly collect garbage with "full memory". Just try to allocate more than yours, which will fail, but only until all SoftReference are cleared.

+3
source

Source: https://habr.com/ru/post/1309462/


All Articles