A new answer to an old question; I found your question as I am dealing with the same problem: I want to write unit test to verify that my class under testing does something very specific if the WeakReference referent becomes zero.
First I wrote a simple test case that would set the referent to null; then call System.gc()
; and interestingly enough: at least in my eclipse, it was โgood enoughโ for my weakRefernce.get()
to return null.
But who knows if this will work for all future environments that will run this unit test in the coming years.
So, after thinking a little more:
@Test public void testDeregisterOnNullReferentWithMock() { @SuppressWarnings("unchecked") WeakReference<Object> weakReference = EasyMock.createStrictMock(WeakReference.class); EasyMock.expect(weakReference.get()).andReturn(null); EasyMock.replay(weakReference); assertThat(weakReference.get(), nullValue()); EasyMock.verify(weakReference); }
Works well too.
Meaning: The general answer to this problem is a factory that creates a WeakReference for objects for you. So, when you want to test your production code; you provide it with a factory; and that the factory will in turn mock WeakReference objects; and now you have complete control over the behavior of this weak reference object.
And โfull controlโ is much better than assuming that the GC may do what you hope it does.
source share