How to mock a static variable in java using JMock

喜夏-厌秋 提交于 2019-12-10 23:14:35

问题


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.


回答1:


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;
    }

}



回答2:


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 :)




回答3:


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;

    }


来源:https://stackoverflow.com/questions/1393029/how-to-mock-a-static-variable-in-java-using-jmock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!