Skip to content

Commit 0107b24

Browse files
author
Richard Jones
committed
Fix unit test by makinig getField use the field name directly
1 parent 7cf5b32 commit 0107b24

File tree

1 file changed

+5
-9
lines changed

1 file changed

+5
-9
lines changed

singleton/src/test/java/com/iluwatar/singleton/LazyLoadedSingletonThreadSafetyTest.java

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -73,20 +73,16 @@ public void test_MultipleCallsReturnTheSameObjectInDifferentThreads() throws Int
7373

7474
@Test
7575
@SuppressWarnings("unchecked")
76-
public void test_HoleInSingletonCreationIfUsingReflection() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
77-
Field[] f = ThreadSafeLazyLoadedIvoryTower.class.getDeclaredFields();
78-
for (Field ff : f) {
79-
System.out.println(ff.getDeclaringClass());
80-
}
81-
assertEquals("One field only in ThreadSafeLazyLoadedIvoryTower", 1, f.length);
82-
f[0].setAccessible(true);
76+
public void test_HoleInSingletonCreationIfUsingReflection() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
77+
Field f = ThreadSafeLazyLoadedIvoryTower.class.getDeclaredField("instance");
78+
f.setAccessible(true);
8379

8480
{//reflectively create an object - the singleton field is null
8581
Class lazyIvoryTowerClazz = Class.forName("com.iluwatar.singleton.ThreadSafeLazyLoadedIvoryTower");
8682
Constructor<ThreadSafeLazyLoadedIvoryTower> constructor = lazyIvoryTowerClazz.getDeclaredConstructor();
8783
constructor.setAccessible(true);
8884
ThreadSafeLazyLoadedIvoryTower instance = constructor.newInstance();
89-
assertNull(f[0].get(instance));
85+
assertNull(f.get(instance));
9086
}
9187

9288
//instantiate the singleton but when we do the below code we are creating a new object where it is set to null still
@@ -97,7 +93,7 @@ public void test_HoleInSingletonCreationIfUsingReflection() throws ClassNotFound
9793
Constructor<ThreadSafeLazyLoadedIvoryTower> constructor = lazyIvoryTowerClazz.getDeclaredConstructor();
9894
constructor.setAccessible(true);
9995
ThreadSafeLazyLoadedIvoryTower instance = constructor.newInstance();
100-
assertNull(f[0].get(instance));
96+
assertNull(f.get(instance));
10197
}
10298
}
10399

0 commit comments

Comments
 (0)