ber*_*tie 5 java testng spring-test
我想在我的@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 */
}
Run Code Online (Sandbox Code Playgroud)
这是运行测试时的错误消息:
FAILED CONFIGURATION: @BeforeTest registerWebScopes
java.lang.NullPointerException
at my.MyBaseTest.registerWebScopes(MyBaseTest.java:22)
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());
}
Run Code Online (Sandbox Code Playgroud)
这些@BeforeMethod也有效(正如您所提到的),因为它们在@BeforeClass方法之后运行。
| 归档时间: |
|
| 查看次数: |
3809 次 |
| 最近记录: |