【发布时间】: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