首页 > 解决方案 > 使用 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()执行没有任何错误并且驱动程序错误没有显示在那里?

标签: selenium-webdrivertestng-eclipse

解决方案


您正在方法内部实例化driver变量,OpenTheSuperAdmin因此它超出了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
        
        }
    }

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


推荐阅读