Java 黄瓜4:实现全局钩子
我对Cucumber BDD测试v4.1还不熟悉 问题: 如何在黄瓜四刀、春播前推进设置方法?Java 黄瓜4:实现全局钩子,java,cucumber-jvm,Java,Cucumber Jvm,我对Cucumber BDD测试v4.1还不熟悉 问题: 如何在黄瓜四刀、春播前推进设置方法? 请帮忙。谢谢 黄瓜钩–在何处使用@之前 @Before在其最基本的用法中允许您在每个场景之前运行一段代码。通常在Cucumber中,我们倾向于做与初始化相关的事情——比如在给定语句中进行对象初始化、数据设置等。正因为如此,很多人不认为有必要在以前使用Cucumber's@。但您可以使用@Before在报告中输入正在执行的新场景。因为@Before总是在每个场景之前运行,所以您可以在报告中使用它来清楚地
请帮忙。谢谢 黄瓜钩–在何处使用@之前 @Before在其最基本的用法中允许您在每个场景之前运行一段代码。通常在Cucumber中,我们倾向于做与初始化相关的事情——比如在给定语句中进行对象初始化、数据设置等。正因为如此,很多人不认为有必要在以前使用Cucumber's@。但您可以使用@Before在报告中输入正在执行的新场景。因为@Before总是在每个场景之前运行,所以您可以在报告中使用它来清楚地描述场景开始执行的时间 没有必要在每个要素文件中添加@Before。只需将其添加到任何一个功能文件中,并让Cucumber完成其工作。Cucumber将找出您之前在哪里保存了@,然后在所有场景之前使用它。为了使您的报告更有用、更容易理解,您实际上也可以在报告中写入场景名称。下面给出了这方面的Java代码-
@Before
public void before(Scenario scenario) {
System.out.println("------------------------------");
System.out.println("Starting - " + scenario.getName());
System.out.println("------------------------------");
}
Cucumber API提供了一个名为Scenario的接口,使用该接口可以获取此类的can实例。在上面的代码中,我们刚刚使用此接口的getName方法在日志中打印场景名称
使用单个场景测试挂钩示例:
特征文件
Feature: Test Hooks
Scenario: This scenario is to test hooks functionality
Given this is the first step
When this is the second step
Then this is the third step
步骤定义:
package stepDefinition;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class Hooks_Steps {
@Given("^this is the first step$")
public void This_Is_The_First_Step(){
System.out.println("This is the first step");
}
@When("^this is the second step$")
public void This_Is_The_Second_Step(){
System.out.println("This is the second step");
}
@Then("^this is the third step$")
public void This_Is_The_Third_Step(){
System.out.println("This is the third step");
}
}
钩子
编辑:
在和其他地方提到的解决方法是在runner类中使用JUnit的@BeforeClass和@AfterClass注释,如下所示:
@RunWith(Cucumber.class)
@Cucumber.Options(format = {
"html:target/cucumber-html-report",
"json-pretty:target/cucumber-json-report.json"})
public class HooksTest {
@BeforeClass
public static void setup() {
System.out.println("Ran the before");
}
@AfterClass
public static void teardown() {
System.out.println("Ran the after");
}
}
注意:虽然@BeforeClass和@AfterClass一开始看起来可能是最干净的解决方案,但它们并不实用。只有当JVM设置为使用JUnit runner时,它们才起作用。其他的运行程序,比如TestNG、命令行运行程序和特殊的IDE运行程序,不会使用这些钩子。他们的方法也必须是静态的,并且无论如何都需要静态变量或单例来共享数据
我已经得到了答案,这是实现ConcurrentEventListener @Before将为所有功能文件运行。我只想对所有场景初始化一次DAO和Spring。我不想,因为它在CI/CD上运行时不起作用。如何在cmd上运行Junit测试?@nicholas希望这有助于解决jvm全局钩子问题@nicholas更新了答案并提供了详细信息。
@RunWith(Cucumber.class)
@Cucumber.Options(format = {
"html:target/cucumber-html-report",
"json-pretty:target/cucumber-json-report.json"})
public class HooksTest {
@BeforeClass
public static void setup() {
System.out.println("Ran the before");
}
@AfterClass
public static void teardown() {
System.out.println("Ran the after");
}
}