views:

316

answers:

2

Hello,

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

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

}
JamesC
A: 

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

Steve Freeman
True, but in the real world you don't always have this option :)
JamesC