Question

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.

Was it helpful?

Solution

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

}

OTHER TIPS

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;

    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top