如何使用cucumber在springjava集成测试中初始化环境变量?

pwuypxnk  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(471)

我将以下环境变量添加到项目的属性文件(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 {

}
fae0ux8s

fae0ux8s1#

您正试图通过注解junitrunner类来让cucumber了解您的spring应用程序上下文配置。但是cucumber集成了多个测试框架,并且有自己的cli。因此,注解junitrunner类并不总是有效的(例如,当cli启动时)。
为此,可以使用@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 {

}

注意:配置类的包应该在粘合路径上。未定义时,它默认为runner类的包。

jaxagkaj

jaxagkaj2#

谢谢所有想帮忙的人。我将分享我如何解决它,我实际上不需要使用 @TestPropertySource 或者 @SpringBootTest ,我只是改变了在集成测试调用的服务中声明变量的方式。
之前:

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

之后:

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

因此,如果测试无法查看属性中声明的内容,则在变量中设置值5。对于代码的其余部分,属性中的变量仍然是:


# variables

limit=5

配置类如下所示:

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

}

相关问题