Access spring context in testng @BeforeTest

I would like to register some web areas in a spring context in my method @BeforeTest. But it turns out that the spring context is still nullat this point.

The test passes fine though, if I go in @BeforeMethod. I wonder how I can access the context in @BeforeTest, because I do not want the area registration code to be repeated for each testing method.

Below are my code snippets.

public class MyTest extends MyBaseTest {
    @Test public void someTest() { /*...*/ }
}

@ContextConfiguration(locations="/my-context.xml")
public class MyBaseTest extends AbstractTestNGSpringContextTests {
    @BeforeTest public void registerWebScopes() {
        ConfigurableBeanFactory factory = (ConfigurableBeanFactory)
                this.applicationContext.getAutowireCapableBeanFactory();
        factory.registerScope("session", new SessionScope());
        factory.registerScope("request", new RequestScope());
    }   

    /* some protected methods here */
}

Here is the error message when starting the test:

FAILED CONFIGURATION: @BeforeTest registerWebScopes
java.lang.NullPointerException
    at my.MyBaseTest.registerWebScopes (MyBaseTest.java:22)
+5
source share
2 answers

springTestContextPrepareTestInstance() BeforeTest.

+12

TestNG @BeforeTest @BeforeClass. springTestContextPrepareTestInstance() @BeforeClass applicationContext. applicationContext - null @BeforeTest. @BeforeTest wapping . ( @Test, ).

@BeforeTest , , @BeforeClass ( , @Test ). , springTestContextPrepareTestInstance,

@BeforeClass(dependsOnMethods = "springTestContextPrepareTestInstance")
public void registerWebScopes() {
    ConfigurableBeanFactory factory = (ConfigurableBeanFactory) 
            this.applicationContext.getAutowireCapableBeanFactory();
    factory.registerScope("session", new SessionScope());
    factory.registerScope("request", new RequestScope());
}   

@BeforeMethod ( ), @BeforeClass.

+2

All Articles