简体   繁体   中英

AbstractApplicationContext has not been refreshed yet exception

I have a standalone jar application which uses spring context as below:

class MainClass {    
    public static void main(final String[] args) {
        AbstractApplicationContext applicationContext = new 
        GenericXmlApplicationContext("file-path-to-xml-config");
        ClassA classA = applicationContext.getBean(ClassA.class);
        ...
    } 
}

Am trying to integration-test above method as below:

@ContextConfiguration(locations = { "file-path-to-test-xml-config" })
public class AbstractIT extends AbstractTestNGSpringContextTests {
    @Inject
    private ClassB classB;

    @Test
    public void testMain() {
        classB.someMethod();
        MainClass.main(null);
    }
}

Above setup throws below exception:

java.lang.IllegalStateException: org.springframework.context.support.AbstractApplicationContext__Generated_OpenPojo@356f20b7 has not been refreshed yet

It seems like creating context from within test case as well as from within main is clashing and thus it is throwing an exception while instantiating it from main method.

I don't want to change spring initialization from within main method as this is a standalone application. Also, I wanted to load spring context in test as am loading test-context in the test.

Is there a way I can get rid of this exception?

I would suggest not to call main method from your test. How about moving the code inside main method to a separate class or method and call it from main? It will be more modular and testable code.

While calling an integrating test, you load your context/application which is similar to calling main. So better to test the modular code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM