Springboot/Cucumber 集成-如何在步骤定义类中使用@Autowired(或其他 SB 标签)?

Shi*_*Tim 5 java cucumber spring-boot

我正在尝试创建一个 Springboot、cucumber 和 Junit4 自动化框架。我使用的版本如下:

  • 弹簧靴:2.1.3
  • 黄瓜:io.cucumber 4.2.3
  • Junit4:4.12
  • 操作系统:Win7 Pro。

我创建了一个 prop 类,它试图从属性文件 (.yml) 中获取属性

道具类:

@Data
@Component
public class PropsConfig {
    @Value("${spring.skyewss}")
    public String url;
}
Run Code Online (Sandbox Code Playgroud)

步骤定义:

public class SkyeWssLoginStepDef implements En {

    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    private WebDriver driver;
    private SkyeWssLoginPage loginPage;
    private SkyeWssUtil skyeWssUtil;
    @Autowired
    private PropsConfig propsConfig;

    public SkyeWssLoginStepDef() {


        Given("^I open Skye WSS web page$", () -> {
            driver = CukeHook.driver;
            loginPage = new SkyeWssLoginPage(driver);
            driver.get(propsConfig.getUrl());
            skyeWssUtil = new SkyeWssUtil();
            LOGGER.info("Current page is " + driver.getTitle());
        });
       }
       ......
     }
Run Code Online (Sandbox Code Playgroud)

黄瓜赛跑班:

@RunWith(Cucumber.class)
@CucumberOptions(
        features = {"src/test/resources/features"},
        plugin = {"pretty", "html:target/cucumber-html-report"},
        tags = {"@SkyeWss"}
)
@SpringBootTest
public class WssRegApplicationTests {

}
Run Code Online (Sandbox Code Playgroud)

我试图在 stepdef 类上提供标签,但没有运气。当我给出@Component 或@SrpingBootTest 之类的stepdef 类标签时,我会收到错误消息。

黄瓜.runtime.CucumberException:胶水类 com.flexicards.wss_reg.skye.step.SkyeWssLoginStepDef 和类 com.flexicards.wss_reg.skye.step.SkyeWssDashboardValStepDef 都试图配置弹簧上下文。请确保只有一个胶水类配置弹簧上下文


黄瓜.runtime.CucumberException: 胶水类 com.flexicards.wss_reg.skye.step.SkyeWssDashboardValStepDef 用@Component 注释;将其标记为 Spring 自动检测的候选对象。胶水类别由 Cucumber 检测和注册。spring 自动检测胶水类可能会导致重复的 bean 定义。请删除@Component注解

我是 Spring 和 Springboot 的新手,我很确定我没有在某个地方正确配置。大多数 springboot 和黄瓜的例子已经过时了。我已经试过了。就像创建一个由所有 stepdefs 类扩展的抽象类。这会给我与@SpringBootTest 相同的错误。

有人可以帮我吗?欢迎任何输入。非常感谢。

mpk*_*nje 6

看起来你几乎做对了所有事情。唯一不合适的是上下文配置的位置。它必须在带有步骤或钩子定义的文件中。否则 Cucumber 不会检测到它。这应该可以解决问题:

@SpringBootTest
@AutoConfigureMockMvc
public class CucumberContextConfiguration  {

    @Before
    public void setup_cucumber_spring_context(){
        // Dummy method so cucumber will recognize this class as glue
        // and use its context configuration.
    }
} 
Run Code Online (Sandbox Code Playgroud)

您可以cucumber-springCucumber github repository 中找到一个工作示例。

也许还值得记住的是,Cucumber 将步骤定义实现为 spring bean,而不是像您期望的那样后期处理单元测试类。这意味着@MockBean,@SpyBean和朋友将不起作用。

编辑:

使用 Cucumber v6.0.0,您可以省略 dummy 方法,而是使用@CucumberContextConfiguration注释。

@SpringBootTest
@CucumberContextConfiguration
public class CucumberContextConfiguration  {

} 
Run Code Online (Sandbox Code Playgroud)

  • 这对我不起作用, @Autowired 属性在 StepDef 类中保持为 null (2认同)