java Cucumber钩子正在运行,但没有测试
我得到一个错误:cucumber.runtime.CucumberException: Failed to instantiate class steps.MyStepdefs
这就是我要做的。我的挂钩位于包steps
中:
public class hooks {
public static WebDriver webDriver;
@Before
public static void ChromeDriverSetup() {
System.out.println("Creating new ChromeDriver instance...");
webDriver = new ChromeDriver();
System.out.println("Hello from hooks!");
}
以上是执行
但是MyStepdefs
测试类不执行(它也在steps
包中)&;我得到了上面的错误
public class MyStepdefs {
ProductPage productPageObjects = new ProductPage();
@Given("I purchase {int} items of the same product")
public void iPurchaseItemsOfTheSameProduct(int qty) {
System.out.println("Hello from MySteps!");
productPageObjects.Visit();
productPageObjects.ClickPlusQtyElement(qty);
}
package pageobjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import static steps.hooks.webDriver;
public class ProductPage {
private WebElement totalQtyElement = webDriver.findElement(By.cssSelector(".sanitized"));
private WebElement plusQtyElement = webDriver.findElement(By.cssSelector(".sanitized"));
public void Visit() {
webDriver.get("https://www.example.com");
}
public String ClickPlusQtyElement(int qty) {
int minAmount = 1;
while (minAmount < qty)
{
plusQtyElement.click();
minAmount ++;
}
System.out.println("The amount is now: " + totalQtyElement.getText());
return totalQtyElement.getText();
}
}
在IntelliJ中,我的glue
设置为steps
。我在steps
包中还有一个RunCucumberTest
类
package steps;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@CucumberOptions(tags = "not @ignore", plugin = {"pretty", "html:target/cucumber"})
public class RunCucumberTest {}
为什么它不执行MyStepsdefs
堆栈跟踪:https://pastebin.com/X5KhHfuP
Update:当我注释掉对ProductPage
的调用时,System.out.println("Hello from MySteps!");
行会被执行。因此,这个特别的电话有一个问题
# 1 楼答案
如果您分析stacktrace,那么我们会看到NullPointerException在类内ProductPage的16行发生。java
请检查上行的初始化,因为下面代码productPageObjects行中可能正在使用该引用。拜访()强>
# 2 楼答案
问题出在你的产品页面上。在实例化这两个web元素字段时:
你会得到一个空指针异常
为什么??因为此时
@Before
钩子还没有运行,当您试图实例化ProductPage时,webDriver
仍然为空我建议将所有这些调用(
webDriver.findElement
)移动到步骤定义内或从步骤定义调用的方法内。通过这种方式,您可以确保实例化的顺序不会给您带来问题# 3 楼答案
好吧,我知道了。当我尝试实例化类
ProductPage
时,由于web驱动程序调用,我得到一个错误,即private WebElement totalQtyElement = webDriver.findElement(By.cssSelector(".sanitized"));
问题是我还没有访问过URL!因此,我将把上述内容放在一个方法中,并进行一些重构