How to mock a static variable in java using JMock
-
21-09-2019 - |
문제
I have a Unit testing problem where a class has a static variable which wants to load the Spring Application Ctx.
This class DOES NOT come out of the Bean Factory and I cannot change this fact.
static ApplicationContext applicationContext = ...;
This works fine, but is hard to JMock, or atleast I don't know a way and until I can the Spring Ctx wants to start up. Not ideal for a unit test situation.
Is there a work around that anyone knows? I have the option to change the static variable to anything I wish..
Thanks.
해결책
Solved this myself.
Was really simple in the end. Justed need to wrap my static in a class which I could then mock.
public class ApplicationContextHolder implements ApplicationContextHoldable {
protected static ApplicationContext applicationContext = ...;
@Override
public ApplicationContext getApplicationContext() {
return ApplicationContextHolder.applicationContext;
}
}
다른 팁
Nice. The irony is that the one thing that Spring is good at is managing Singletons, so there shouldn't be a need for static variables :)
You can use reflection based JMock APIs to set private / static fields
import static mockit.Deencapsulation.setField;
//Test method
public void testSample {
setField(Sample.class,"isPrivate",true);
setField(Sample.class,"isStatic",true);
}
private class Sample {
private boolean isPrivate = false;
private boolean isStatic = false;
}