簡體   English   中英

從 Spring 引導 Cucumber 測試中的屬性文件動態更改值

[英]Dynamically change value from a property file in Spring Boot Cucumber test

我有一個 Spring 引導應用程序,其中特定的 bean (MyClass) 獲得一個 @Value 注釋屬性,其值在application.properties文件中定義:

@Component
public class MyClass {
    
  private String type;

  public MyClass(@Value("${type}") String type) { 
    this.type=type;
  }

  public String doSomething () {...} 
}

application.properties文件包括以下內容: type=typeA

測試是使用 Cucumber 完成的,我想在type的值不是typeA而是typeB時測試MyClass.doSomthing方法的行為,所以我考慮執行以下操作:

*.feature文件中的場景將像這樣開始:

Scenario: Validating doSomething when type is B
    Given The value of type is typeB
    Then Validate doSomething 

*StepDef文件中 - Given步驟的實現應該以某種方式將type的值更改為typeB ,以便MyClass.doSomthing的流程將處理typeB

@Given("The value of type is typeB")
public void changeTypeToB() {
    ...
}

我的問題是:考慮到在測試期間 Spring 配置文件是默認配置文件的事實,我如何將type的值設置為typeB (在方法changeTypeToB中),因此type的初始值為typeA

謝謝!

迪諾

在 Spring 應用程序已經啟動之后,您實際上是在嘗試更改配置值。

這通常需要啟動一個新的應用程序上下文,在 Cucumber 術語中,這意味着啟動一個單獨的測試套件。

你會這樣組織:

package com.example.stepdefinitions;

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(
  extraGlue = "com.example.app.config.typea"
)
public class RunCucumberTestTypeA {

}

和:

package com.example.stepdefinitions;

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(
  extraGlue = "com.example.app.config.typeb"
)
public class RunCucumberTestTypeB {

}

然后使用上下文配置覆蓋屬性:

package com.example.app.config.typeb;

@CucumberContextConfiguration
@SpringBootTest(properties = {
        "com.example.value=Hello", 
        "com.example.value2=World"
})
public class CucumberTestContextConfiguration {

}

或者啟用配置文件並將您的屬性放入application-type-b.yml

package com.example.app.config.typeb;

@CucumberContextConfiguration
@SpringBootTest
@ActiveProfiles("type-b")
public class CucumberTestContextConfiguration {

}

作為健全性檢查,您可以驗證在The value of type is typeB步驟中是否使用了正確的配置。

這是相當多的設置。 您還可以創建不受 spring 應用程序上下文管理的MyClass的新實例並在其上運行測試。

@Given("The value of type is typeB")
public void changeTypeToB() {
    testInstance = new MyClass("typeB")
}
@Then("validate doSomething")
public void changeTypeToB() {
    testInstance.doSomething()
    // validate test instance did something
}

最后,您可能需要重新考慮您的設計。 聽起來typeB可能是一個功能切換(因為您想在運行時更改它)在這種情況下使用@Value將不是正確的方法。

暫無
暫無

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

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