![](/img/trans.png)
[英]dynamically load test property file and service property file in spring boot
[英]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.