Accessing spring context in testng's @BeforeTest

跟風遠走 提交于 2020-01-01 10:28:15

问题


I would like to register some web scopes to the spring context in my @BeforeTest method. But it turns out that spring context is still null at that point.

The test runs fine though, if I change into @BeforeMethod. I wonder how I can access the context in @BeforeTest, because I don't want the scope registration code to be repeated for each test methods.

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's the error message when running the test:

FAILED CONFIGURATION: @BeforeTest registerWebScopes
java.lang.NullPointerException
    at my.MyBaseTest.registerWebScopes(MyBaseTest.java:22)

回答1:


Call springTestContextPrepareTestInstance() in your BeforeTest method.




回答2:


TestNG runs @BeforeTest methods before @BeforeClass methods. The springTestContextPrepareTestInstance() is annotated with @BeforeClass and sets up the applicationContext. This is why the applicationContext is still null in a @BeforeTest method. @BeforeTest is for wapping a tagged group of tests. (It does not run before each @Test method, so it's a bit of a misnomer).

Instead of using @BeforeTest, you should probably use @BeforeClass (which is run once, before the first @Test in the current class). Be sure it depends on springTestContextPrepareTestInstance method, as in

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

The @BeforeMethod works, too (as you mentioned) because they run after @BeforeClass methods.



来源:https://stackoverflow.com/questions/10184602/accessing-spring-context-in-testngs-beforetest

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