views:

74

answers:

1

To get any code with SoftReference<T> to be fully tested, one must come up with some way to test the 'yup, it's been nulled' case. One might more or less mock this by using a 'for-test' code path to force the reference to be null, but that won't manage the queue exactly as the GC does. I wonder if anyone out can share experience in setting up a repeatable, controlled, environment, in which the GC is, in fact, provoked into collecting and nulling?

+1  A: 

I would break the problem up into two parts:

  1. Testing the code path when null is returned.
  2. Testing the SoftReference.

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

The next is really an integration test, to see if the GC's behavior WRT SoftReference is as you expect. I'm not sure I would go to the effort to fully automate such a test, except in perhaps the larger context of load testing, but if that is important I would spin up a JVM with a very tight maximum amount of memory and load up enough memory to trigger soft-reference collection. The failing path would be to have the code not use a soft-reference, the memory loaded up should cause an OutOfMemory error. Then make the tests pass by converting to a soft-reference. The purpose of the tests should be to assert the assumptions made in the unit tests about the behavior.

Yishai