【问题标题】:Passing scenario context between multiple step definition classes在多个步骤定义类之间传递场景上下文
【发布时间】:2019-04-24 22:28:53
【问题描述】:

所以,我开始使用 Cucumber/TestNG/Java/selenium 开发一个框架 我有一个上下文类,它在枚举的帮助下以键值对的形式保存场景上下文 引用自here

我的问题是: 对于功能中的特定场景,步骤定义在多个类中定义:

示例特征

Feature: A feature
Scenario: Scenario
Given Statement 1
Then Statement 2

第一类

Class firstDef{
TestRunner test;
public firstDef(TestRunner test){
this.test = test
}
Brain context = new Brain();
@Given("Statement1")
void method1(){
}
}

2 级

Class secondDef{
TestRunner test;
public secondDef(TestRunner test){
this.test = test
}
Brain context = new Brain();
@Given("Statement2")
void method1(){
}
}

TestRunner 类

Class TestRunner{
//some code
@Test
public method1(){
//some code
}
}

所以,

每个步骤定义的大脑类对象都会不同,这无济于事,因为我希望整个场景中的上下文都相同

即使我在 Runner 类中实例化 Brain,该实例对于测试类的每个实例都是新的

为了克服这个问题,我想到的一种可能的解决方案是序列化和反序列化

在@BeforeClass 方法中,我会有:

File f = new File(path);
if(!f.exists()){
Brain context = new Brain();
FileOutputStream fos = new FileOutputStream(name);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(context);
}

然后我可以在任何我想要上下文的地方反序列化,并在对同一个引用变量进行更改后再次序列化

上述方法正确还是有更好的方法来解决同样的问题

【问题讨论】:

  • 通过使用黄瓜 picocontainer 在步骤定义类中使用带有构造函数注入的 DI。对于一个场景,DI 容器将注入对象的相同实例。另外,为什么要将 testrunner 传递给步骤定义类?
  • @Grasshopper,谢谢。我不知道 pico 容器。场景现在运行良好
  • 关于 testrunner,我的 WebDriverManager 没有完成,所以我通过一个方法直接从 TestRunner 类中获取驱动程序实例。不是一个好方法,但我期待尽快纠正这个问题
  • Google ThreadLocal 用于存储特定于线程的驱动程序实例。也非常适合并行运行。

标签: java automation cucumber testng


【解决方案1】:

使用 Cucumber PicoContainer 进行构造函数注入就像解决上述问题的魅力

只需添加依赖:

<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-picocontainer -->
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-picocontainer</artifactId>
        <version>1.2.5</version>
        <scope>test</scope>
    </dependency>

到您的 pom.xml(对于 Maven 项目)并通过多个步骤定义类传递 HashMap 类的引用变量,它在一个场景中将保持不变。

详细解释请看this文章

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-25
    • 2023-02-16
    • 1970-01-01
    • 2021-12-06
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多