尝试使用TestNG执行跨浏览器测试脚本但给出错误“FAILED CONFIGURATION:@BeforeTest Browser(null)”

时间:2018-02-19 05:16:57

标签: java testng

尝试使用TestNG执行跨浏览器测试脚本,但出现错误“FAILED CONFIGURATION:@BeforeTest Browser(null):java.lang.NullPointerException”

这是我的代码:

public class CrossBrowserTestingFile {
WebDriver driver;
  @BeforeTest
  @Parameters("browser")
  public void Browser(@Optional String browser)throws Exception {
    //Check if parameter passed from TestNG is 'firefox'
            if(browser.equalsIgnoreCase("firefox")){
            //create firefox instance
                System.setProperty("webdriver.firefox.marionette", ".\\geckodriver.exe");
                driver = new FirefoxDriver();
            }
            //Check if parameter passed as 'chrome'
            else if(browser.equalsIgnoreCase("chrome")){
                //set path to chromedriver.exe
                System.setProperty("webdriver.chrome.driver",".\\chromedriver.exe");
                //create chrome instance
                driver = new ChromeDriver();
            }
            else
            {
                //If no browser passed throw exception
                throw new Exception("Browser is not correct");
            }
            }
  @Test
  public void testParameter() throws InterruptedException{
        driver.get("http://demo.guru99.com/V4/");
        //Find user name
        WebElement userName = driver.findElement(By.name("uid"));
        //Fill user name
        userName.sendKeys("guru99");
        //Find password
        WebElement password = driver.findElement(By.name("password"));
        //Fill password
        password.sendKeys("guru99");
  }
}

请帮助,TIA。

1 个答案:

答案 0 :(得分:0)

问题是您没有为@BeforeTest中的浏览器风格提供值,只是为了确保TestNG不会抱怨,您将参数标记为@Optional。因此,browser方法中参数Browser()的值为空。

所以当Java试图执行时

if(browser.equalsIgnoreCase("firefox"))

你最终会触发NullPointerException

您可以通过将代码更改为

来超越NullPointerException
if("firefox".equalsIgnoreCase(browser))

这两个条件。一旦你这样做,你就会开始看到异常

"Browser is not correct"

为确保您的browser参数始终具有值,您可以执行以下操作之一。

  • 运行测试时,通过JVM参数-Dbrowser=firefox传递参数的值(是的,TestNG允许您通过JVM参数传递由@Parameters注释驱动的参数值。有关详细信息,请参阅查看我的博文here (或)
  • 您创建了一个套件xml文件,其中使用browser<parameter name="browser" value="firefox"/>提供了值,然后始终使用套件xml文件运行测试。

<强>记住:

每个@BeforeTest标记仅执行

<test>。因此,如果您有两个或更多@Test方法(位于子类中)尝试使用通过一个driver初始化的@BeforeTest实例,那么您可能会遇到NullPointerException

由于您还没有显示TestNG套件xml文件的外观,因此很难发表评论。我建议您在StackOverFlow中发布一个新问题。

相关问题