Loading...

November 15, 2010

Set the Value of a Static Property with the Java Reflection API

Recently I was working on a legacy Java project without any unit tests. Just to get started I wanted to write some unit tests, so I could understand better what was happening in the code. But the code wasn't created to be easily unit tested. Therefore I had to resort to some Reflection API code to set the value of a static property of a class that was used in the code under test. Because the property is static we must pass null as an argument for the Reflection API Field.set() method.

package com.mrhaki.java;

public class MainTest {
    @org.junit.Test
    public void main_success() {
        ...
        mockThreadLocal();
        ...
        assertEquals("mrhaki", Holder.getValue());
    }

    private void mockThreadLocal() {
        ThreadLocal mockThreadLocal = new ThreadLocal<String>();
        mockThreadLocal.set("mrhaki");

        Field threadLocalField = Holder.class.getDeclaredField("valueThreadLocal");
        threadLocalField.setAccessible(true);
        threadLocalField.set(null, mockThreadLocal);
    }
}
package com.mrhaki.java;

public class Holder {
    private static ThreadLocal<String> valueThreadLocal = new ThreadLocal<String>();

    public static String getValue() {
        return valueThreadLocal.get();
    }
}