首页 > 解决方案 > 无法读取硒中的属性文件(对象存储库)

问题描述

这是我得到的错误

FAILED CONFIGURATION: @BeforeTest beforetest 
java.lang.NullPointerException

这是我的配置阅读器类来加载我的属性文件

public  static void Configreader() {
    try {
        File src = new File("./src/test/resources/config.properties");
        FileInputStream fis = new  FileInputStream(src);
        pro = new Properties();
        pro.load(fis);
        System.out.println("Property class loaded");
    } catch (Exception e) {
        System.out.println("Exception is" +e.getMessage());
    }
}

这是我的测试类,我想在其中访问我的 webelements

public class LoanDetails extends Configreader {

    static Properties pro;
    WebDriver driver;

    @BeforeTest
    public  void beforetest() throws Exception { 
        Configreader();
        driver = Browser.GetBrowser();
        System.out.println(" value  is " +pro.getProperty("account_xpath"));
    }
}

我需要访问我的 webelement(“account_xpath”),否则一切正常

我已将我的属性文件附在下面我需要访问我的 webelement (account_xpath) 的位置

在此处输入图像描述

标签: javaselenium

解决方案


你得到空指针异常是因为

  1. 您已经在 LoanDetails 类中再次创建了一个新的 Properties 类引用并使用了它。

  2. 您的 Configreader 方法永远不会被调用,因为 Configreader 类中没有 testng 注释,因此 testng 将跳过它。

解决方案 -

  1. 将 Configreader 方法设为静态
  2. 将属性类 obj ref 设为静态
  3. 在测试前调用 Configreader 方法
  4. 属性值将在没有 NullPointerException 的情况下工作

试试下面的代码 -

package com.example;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

public class Configreader {

    // make property as static
    public static Properties pro;

    // make method as static
    public static void ConfigFileReader() 
      {
             try {
                  File src = new File("./src/test/resources/config.properties");
                  FileInputStream fis = new  FileInputStream(src);
                  pro = new Properties();
                  pro.load(fis);
                  System.out.println("Property class loaded");
              } 
              catch (Exception e) {
                  System.out.println("Exception is" +e.getMessage());
              }
      }
}

package com.example;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;


public class LoanDetails extends Configreader {

    @BeforeTest
    public  void beforetest() throws Exception { 
       // Called this method in before test annotation method  
        ConfigFileReader();    
        //  driver = Browser.GetBrowser();
        System.out.println(pro.getProperty("account_path"));
                driver.findElement(By.xpath(pro.getProperty("account_xpath"))).click();
    }

    @Test
    void testmain() {
        System.out.println("Testng test");
    }
}

在此处输入图像描述


推荐阅读