如果它不能为null,但需要初始化,我该怎么做呢?

时间:2015-10-16 19:23:37

标签: java selenium xpath

我在访问某些xpath时遇到问题。我们使用混合测试框架。

public class logoutMenu {
    public static void run(WebDriver driver) {
        Properties prop = new Properties();
        InputStream selectproductsidebarobjectrepository;
        try {
            selectproductsidebarobjectrepository = new FileInputStream(
                    "C:/thisisthepath/ObjectRepositories/SignInPageObjectRepository");
            prop.load(selectproductsidebarobjectrepository);
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
            WebElement logoutNormal = driver.findElement(By.xpath(prop.getProperty("logoutnormal")));
            Actions actions = new Actions(driver);
            actions.moveToElement(logoutNormal).build().perform();
            WebElement logoutHover = driver.findElement(By.xpath(prop.getProperty("logouthover")));
            logoutHover.click();
            WebElement logoutPushed = driver.findElement(By.xpath(prop.getProperty("logoutpushed")));
            logoutPushed.click();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (selectproductsidebarobjectrepository != null) {
                try {
                    selectproductsidebarobjectrepository.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

原始问题: 它告诉我,如果xpath为null,则无法访问它。由于这一行,它为空:InputStream selectproductsidebarobjectrepository = null;。如果我拿走它的= null;部分,我会得到一个不同的错误:“本地变量selectproductsidebarobjectrepository可能尚未初始化”,这也是有意义的。

我可以使selectproductsidebarobjectrepository等于那个不为空吗?

新问题: 清理代码。摆脱了空。摆脱了额外的支架。仍然会出现:

java.lang.IllegalArgumentException: Cannot find elements when the XPath expression is null.
at org.openqa.selenium.By.xpath(By.java:113)
at SelectProductSidebar.logoutMenu.run(logoutMenu.java:29)
at CommonFunctions.FunctionCheck.test(FunctionCheck.java:19)

以下是调用此类的脚本:

public class FunctionCheck {
    @Test
    public void test() throws Exception {
        WebDriver driver;
        String baseUrl;
        driver = new FirefoxDriver();
        baseUrl = "http://www.MATTDAMON.com/";
        driver.get(baseUrl + "MATT/MATT/MATT/MATT");
        Thread.sleep(3000);
        LoginPage.enterValidCredentials.run(driver);
        SelectProductSidebar.logoutMenu.run(driver);

如果我搞砸了比我最初更多的话(可能是真的),这里是文本文件selectproductsidebarobjectrepository:

logoutnormal=//img[contains(@src,'log_out_normal')]
logouthover=//img[contains(@src,'log_out_hover')]
logoutpushed=//img[contains(@src,'log_out_pushed')]

我可能正在做一些非常愚蠢的事情,但我对现在的情况完全视而不见。

1 个答案:

答案 0 :(得分:2)

移除额外的支撑后,这对我来说很好。

byref