[英]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.