2017-02-22 128 views
0

情況:有一臺服務器可以接受我交給它的測試結果,但只能給予適當的授權和客戶端配置。所以我編寫了一個客戶端類作爲一個bean,它從application.properties中加載了正確的憑據(在您使用憑證和spring的屬性連接到數據庫的同一莊園中)。我現在想編寫一個使用此客戶端的testng偵聽器來執行此操作。做我的研究,我發現春天要做的事情應該是延長AbstractTestExecutionListenerTestExecutionListeners中的Spring Boot autowire依賴關係

所以,如果我自動裝配我的客戶作爲一個類的成員,這樣@Autowired private MyClient client;我可以看到豆被正確創建,但是如果我嘗試使用它在我的聽衆是這樣的:

@TestExecutionListeners(mergeMode = MergeMode.MERGE_WITH_DEFAULTS, listeners = {MyListener.class}) 
public abstract class MyTestParent extends AbstractTestNGSpringContextTests { //... 

我可以看到bean不是自動裝配的,這導致我相信這些監聽器在spring上下文之外被實例化爲bean本身。

我該如何編寫一個監聽器(特定於spring或testng),該監聽器可以將相關性從Spring上下文連接到它?如果我想將結果推送到其他任意的測試結果庫(如數據庫),該怎麼辦?

回答

1

Spring在TestListeners中不自動連接依賴關係。 但是你可以訪問的beanfactory並用它來自動裝配聽者本身:

public class CustomTestExecutionListener extends AbstractTestExecutionListener { 

    @Autowired 
    TestSupport support; 

@Override 
public void beforeTestClass(TestContext testContext) throws Exception { 
    //get the beanfactory and use it to inject into this 
    testContext.getApplicationContext() 
      .getAutowireCapableBeanFactory() 
      .autowireBean(this); 

    //now use the autowired field 
    support.beforeClass(); 
} 

... }

+0

這是不是我最後做,但它直接回答我的問題。謝謝 –