问题描述
我想在我的 @BeforeTest
方法中将一些Web范围注册到spring上下文中。但事实证明,那时春天的上下文仍然是 null
。
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.
测试运行正常但是如果我改为 @BeforeMethod
。我想知道如何在 @BeforeTest
中访问上下文,因为我不希望为每个测试方法重复范围注册代码。
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.
以下是我的代码段。
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)
推荐答案
在BeforeTest方法中调用 springTestContextPrepareTestInstance()
。
Call springTestContextPrepareTestInstance()
in your BeforeTest method.
这篇关于访问testng的@BeforeTest中的spring上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!