如何使用 Cucumber 在 Spring-Java 集成测试中初始化环境变量?

How to initialize environment variable in a Spring-Java integration test using Cucumber?

我在项目的属性文件 (src/test/resources/application.properties) 中添加了以下环境变量:

#variables
  limit=5

我想开发一个集成测试,但它总是出错,因为我的限制变量的值是 0 而不是 5(这是我在属性中设置的值)。我尝试使用 @SpringBootTest 和 @TestPropertySource 但我没有成功,变量仍然为零:

@RunWith(Cucumber.class)
@SpringBootTest(properties = {"limit=5"})
@CucumberOptions(features = { "classpath:project/feature/list" }, plugin = {"pretty" }, monochrome = true)
public class RunCucumberTestIT {

}

@RunWith(Cucumber.class)
@TestPropertySource(properties = {"limit=5"})
@CucumberOptions(features = { "classpath:project/feature/list" }, plugin = {"pretty" }, monochrome = true)
public class RunCucumberTestIT {

}

您正试图通过注释 JUnit 运行程序 class 让 Cucumber 知道您的 Spring 应用程序上下文配置。然而,Cucumber 集成了多个测试框架并拥有自己的 CLI。因此,注释 JUnit 运行器 class 并不总是有效(例如,当 CLI 时)。

因此 you can annotate a configuration class on your glue path with @CucumberContextConfiguration 并使用 @SpringBootTest

使用最新版本的 Cucumber (v6.9.0) 这应该可以工作:

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-spring</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <scope>test</scope>
        </dependency>
package com.example.app;

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

@RunWith(Cucumber.class)
@CucumberOptions(features = { "classpath:project/feature/list" }, plugin = {"pretty" }, monochrome = true)
public class RunCucumberTestIT {

}
package com.example.app;

import org.springframework.boot.test.context.SpringBootTest;

import io.cucumber.spring.CucumberContextConfiguration;

@CucumberContextConfiguration
@SpringBootTest(properties = {"limit=5"})
public class CucumberSpringConfiguration {

}

注意:配置class的包应该在胶路径上。未定义时,它默认为跑步者的包 class.

感谢所有试图提供帮助的人。我将分享我是如何设法解决它的,我实际上并不需要使用 @TestPropertySource@SpringBootTest,我只是更改了我的变量在集成测试调用的服务中声明的方式。

之前:

@Value("${limit}")
private static int dateFilterLimit;

之后:

@Value("${limit:5}")
private int dateFilterLimit;

因此,如果测试未能看到属性中声明的内容,则在变量中设置值 5。对于其余代码,properties 中的变量仍然是:

#variables
limit=5

配置 class 如下所示:

@RunWith(Cucumber.class)
@CucumberOptions(features = { "classpath:project/feature/list" }, plugin = {"pretty" }, monochrome = true)
public class RunCucumberTestIT {

}