运行 使用 TestNG 时无法解析驱动程序

driver cannot be resolved when running using TestNG

  package bannerTstNG;
    
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.testng.annotations.AfterTest;
    import org.testng.annotations.BeforeTest;
    import org.testng.annotations.Test;
    
    public class BannerTestNG {
        
        
        @BeforeTest
        public void OpenTheSuperAdmin() throws InterruptedException {
            System.setProperty("webdriver.chrome.driver","D:\myselenium\bannerTstNG\driver\chromedriver\chromedriver.exe");
            WebDriver driver = new ChromeDriver();
            driver.get("https://ss-superadmin-staging.labaiik.net/");
            driver.manage().window().maximize();
            driver.findElement(By.xpath("//input[@id='email']")).sendKeys("arsalan.hameed@avrioc.com");
            driver.findElement(By.xpath("//input[@id='password']")).sendKeys("admin");
            Thread.sleep(1000);
            driver.findElement(By.xpath("//button[contains(text(),'Login')]")).click();
            Thread.sleep(6000);
        }
    
        @Test
        public void ClickOnBanner() {
            driver.findElement(By.xpath("//body/div[2]/div[1]/div[1]/div[1]/div[3]/div[1]/ul[1]/li[4]/a[1]")).click
        
        }   
    }
    
    

函数OpenTheSuperAdmin()是运行但是当ClickOnBanner()执行时,我得到以下错误:driver cannot be resolved.

为什么 OpenTheSuperAdmin() 没有任何错误地执行并且没有显示驱动程序错误?

您正在 OpenTheSuperAdmin 方法内部实例化 driver 变量,因此它超出了 ClickOnBanner 测试的范围。请尝试以下操作:

    package bannerTstNG;
    
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.testng.annotations.AfterTest;
    import org.testng.annotations.BeforeTest;
    import org.testng.annotations.Test;
    
    public class BannerTestNG {

        private WebDriver driver;        
        
        @BeforeTest
        public void OpenTheSuperAdmin() throws InterruptedException {
            System.setProperty("webdriver.chrome.driver","D:\myselenium\bannerTstNG\driver\chromedriver\chromedriver.exe");

            driver = new ChromeDriver();

            driver.get("https://ss-superadmin-staging.labaiik.net/");
            driver.manage().window().maximize();
            driver.findElement(By.xpath("//input[@id='email']")).sendKeys("arsalan.hameed@avrioc.com");
            driver.findElement(By.xpath("//input[@id='password']")).sendKeys("admin");
            Thread.sleep(1000);
            driver.findElement(By.xpath("//button[contains(text(),'Login')]")).click();
            Thread.sleep(6000);
        }
    
        @Test
        public void ClickOnBanner() {
            driver.findElement(By.xpath("//body/div[2]/div[1]/div[1]/div[1]/div[3]/div[1]/ul[1]/li[4]/a[1]")).click
        
        }
    }

通过将驱动程序声明为 class 中的一个字段,您现在可以从 class 中的任何测试访问它。