Matt Lachman's answer worked fine for me - until I tried it with Spring. In Spring, I got a run-time exception when trying to change the logger to mockLogger. To make it work in Spring, I had to do the following:
change the line
Whitebox.setInternalState(ClassUnderTest.class, "logger", mockLogger);
to
EncapsulationBreaker.setFinalStatic(ClassUnderTest.class.getDeclaredField("logger"), mockLogger);
and EncapsulationBreaker looks like this:
public class EncapsulationBreaker { public static void setFinalStatic(Field field, Object newValue) throws Exception { field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, newValue); } }
For more information about setting up personal static finite elements, see Change a personal static final field using Java reflection.
Also note: I am only doing this for testing.
source share