簡體   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