繁体   English   中英

访问testng的@BeforeTest中的spring上下文

[英]Accessing spring context in testng's @BeforeTest

我想在@BeforeTest方法@BeforeTest一些Web范围注册到spring上下文中。 但事实证明,春季上下文在那时仍然是null

如果我改成@BeforeMethod ,测试运行正常。 我想知道如何在@BeforeTest访问上下文,因为我不希望为每个测试方法重复范围注册代码。

以下是我的代码片段。

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 */
}

这是运行测试时的错误消息:

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

在BeforeTest方法中调用springTestContextPrepareTestInstance()

TestNG在@BeforeClass方法之前运行@BeforeTest方法。 springTestContextPrepareTestInstance()使用@BeforeClass注释并设置applicationContext 这就是为什么applicationContext@BeforeTest方法中仍然为null @BeforeTest用于@BeforeTest一组标记的测试。 (它不会在每个@Test方法之前运行,所以它有点用词不当)。

您应该使用@BeforeClass (在当前类的第一个@Test之前运行一次),而不是使用@BeforeTest 确保它依赖于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方法之后运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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