【问题标题】:Unable to identify variable even though variable has been defined即使已定义变量也无法识别变量
【发布时间】:2016-10-18 00:58:31
【问题描述】:

我正在尝试使用 Eclipse 和 cucumber 通过 selenium webdriver 在工作中实现自动化。运行功能文件时出现以下错误

java.lang.Error:未解决的编译问题: 驱动无法解决

如下所示,在我的 Tests_Steps.java 类中,我已正确声明了变量“驱动程序”。我还将对象分配给类(FirefoxDriver)的实例。下面是我的代码。

package stepDefinition;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class Tests_Steps {

@Given("^User is on the Home Page$")
    public void user_is_on_the_Home_Page() throws Throwable {
        WebDriver driver=new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        driver.get("http://www.gmail.com/login");
    }

    @When("^User Clicks on the Login$")
    public void user_Clicks_on_the_Login() throws Throwable {
        driver.findElement(By.xpath(".//*[@id='login']")).click();
    }

    @When("^User enters UserName and Password$")
    public void user_enters_UserName_and_Password() throws Throwable {
        driver.findElement(By.id("login")).sendKeys("ab24146_111");
        driver.findElement(By.id("psw")).sendKeys("Password1");
        driver.findElement(By.id("loginButton")).click();
    }

    @Then("^Message displayed LogIn Successfully$")
    public void message_displayed_LogIn_Successfully() throws Throwable {
        System.out.println("Login Successfully");
    }

由于某种原因,我的驱动程序变量在第二步和第三步没有被识别。我看到红色的波浪线,当我将鼠标悬停在红线上时,它说“驱动程序无法解决”在第一步中它工作正常。

你们能帮我解决需要做的事情吗?

【问题讨论】:

  • 那是因为方法中定义的变量只存在于该方法中。
  • 非常感谢!成功了!!

标签: java eclipse selenium selenium-webdriver cucumber


【解决方案1】:

java.lang.Error: Unresolved compiler problem: driver cannot be resolved

实际上,您是在本地 user_is_on_the_Home_Page() 内声明 WebDriver 变量,因此这是有限的,并且仅适用于此方法。

您应该全局声明此变量,该变量可用于所有这些方法,如下所示:-

public class Tests_Steps {

  WebDriver driver = null;

  @Given("^User is on the Home Page$")
  public void user_is_on_the_Home_Page() throws Throwable {
    driver=new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
    driver.get("http://www.gmail.com/login");
  }

  ------------
  ------------
}

【讨论】:

    【解决方案2】:

    您已经在 user_is_on_the_Home_Page() 方法中声明了变量,因此它的范围仅限于该方法,并在该方法完成时被销毁。

    移动成为类的实例变量并在构造函数中对其进行初始化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-13
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 2014-08-21
      相关资源
      最近更新 更多