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();
}
}
1 comments:
Java and to some degree .Net are the main choices because they have been consistently pegged as the “safe” choice to go with for mid-level project managers in the corporate world. No one was ever fired for choosing Java or Microsoft.
However, there are many large distributed applications these days that run primarily with technologies like Python, PHP, et al. Even companies like Google and Yahoo are heavily invested in these technologies. Java may be the main choice for enterprise development now, but it’s days are numbered as the only stalwart option to go with.
Let’s face it, many of these so called “enterprise applications” could easily have been written much faster and with less overhead using technologies like Python, PHP, et al.
OpenCL Training
Post a Comment