![](/img/trans.png)
[英]Can you better explain the semantics of TestNG's @BeforeTest annotation?
[英]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.