Skip to content

Commit 7cf5b32

Browse files
author
Richard Jones
committed
Add additional unit tests to show how lazy loading is working with reflection
1 parent 45b0ac3 commit 7cf5b32

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.iluwatar.lazy.loading;
2+
3+
import org.junit.Test;
4+
5+
import java.lang.reflect.Field;
6+
7+
import static org.junit.Assert.assertEquals;
8+
import static org.junit.Assert.assertNotNull;
9+
import static org.junit.Assert.assertNull;
10+
11+
/**
12+
* Using reflection this test shows that the heavy field is not instantiated until the method getHeavy is called
13+
*
14+
* Created by jones on 11/10/2015.
15+
*/
16+
public class HolderThreadSafeTest {
17+
18+
@Test
19+
public void test() throws IllegalAccessException {
20+
HolderThreadSafe hts = new HolderThreadSafe();
21+
22+
{//first call is null
23+
Field[] f = HolderThreadSafe.class.getDeclaredFields();
24+
assertEquals("One field only in HolderThreadSafe", 1, f.length);
25+
f[0].setAccessible(true);
26+
27+
assertNull(f[0].get(hts));
28+
}
29+
30+
// now it is lazily loaded
31+
hts.getHeavy();
32+
33+
{//now it is not null - call via reflection so that the test is the same before and after
34+
Field[] f = HolderThreadSafe.class.getDeclaredFields();
35+
assertEquals("One field only in HolderThreadSafe", 1, f.length);
36+
f[0].setAccessible(true);
37+
38+
assertNotNull(f[0].get(hts));
39+
}
40+
}
41+
}

0 commit comments

Comments
 (0)