簡體   English   中英

使用彈簧配置文件時自動將bean裝配到TestNG測試的問題

[英]Problems autowiring beans to TestNG test when using spring profiles

我目前正在完善我們擁有的測試框架。 對於當前的需求,我們必須支持多個彈簧曲線,並多次運行測試,每次使用不同的曲線。 每個配置文件針對單獨的測試環境,因此可以執行具有不同邏輯的不同測試集。

我正在上這樣的測試課:

@ContextConfiguration(locations = { "classpath:META-INF/test-context.xml" })
public class Test extends AbstractTestNGSpringContextTests {
    @Autowired
    ProfileSpeciticBean profileSpecificBean;

    ...
}

在這里, ProfileSpecificBean是一個接口,由單獨的類實現。 實際要注入的實現由活動的Spring概要文件確定,我正在使用Spring XML上下文。 我正在使用-Dspring.profiles.active=profileName命令使用Maven構建項目,因此希望測試能夠捕獲通過的概要文件。

但是,當前測試失敗,並在完整的堆棧跟蹤中出現此錯誤:

org.springframework.beans.factory.NoSuchBeanDefinitionException:找不到依賴項ProfileSpeciticBean類型的合格Bean:預計至少有1個合格的autowire候選bean,找到0

在對該主題進行了一些重新研究之后,我發現AbstractTestNGSpringContextTests在測試類的頂部期望有一個@ActiveProfiles批注。 因此,此代碼有效:

 @ContextConfiguration(locations = { "classpath:META-INF/test-context.xml" })
 @ActiveProfiles("profile1")
 public class Test extends AbstractTestNGSpringContextTests ...

問題是:我想避免在類中對配置文件名稱進行硬編碼。 我只需要更改命令行腳本,即可針對不同的配置文件運行相同的測試類。

以上可能嗎? 有什么方法可以使TestNG知道命令行配置文件,並重新使用同一測試? 我需要避免重復代碼和配置來運行測試,因此我不希望為每個配置文件創建兩個Test類。

為了獲得更精確的答案,我建議您添加stacktrace和您的主要配置(在其中聲明了應該由測試bean替換的bean)。

這是一般的想法:

假設您要根據個人資料更改PropertyPlaceholderConfigurer。

腳步:

  1. 您創建包含PropertyPlaceholderConfigurer的main-config.xml並將其標記為profile =“ default”
  2. 使用PropertyPlaceholderConfigurer的測試實現創建test-config.xml
    (不要忘記用profile =“ MyTestProfile”標記test-config.xml或僅用profile =“ MyTestProfile標記PropertyPlaceholderConfigurer)
  3. 比將test-config.xml和main-config.xml都導入到測試中

 @ContextConfiguration(locations = { "classpath:META-INF/main-config.xml","classpath:META-INF/test-config.xml" })
 @ActiveProfiles("MyTestProfile")
 public class Test extends AbstractTestNGSpringContextTests {}

它應該工作。 祝好運。

嘗試遵循如何為Junit單元測試設置JVM參數? 為實際運行測試的虛擬機設置系統變量-與運行maven的虛擬機不同。

在此設置您的個人資料。

您可以使用maven系統參數從maven調用中進行設置(或使用maven配置文件)。

使用 '

[英]Using '<import resource=' on multiple beans profiles in spring?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM