从Selenium中的属性文件获取值时获取NullPointerException

时间:2018-08-07 10:14:52

标签: java selenium selenium-webdriver properties

我正在尝试从属性文件中获取属性(键:值对),但出现了空指针异常。

Properties prop;
@BeforeTest
public void beforeTest() throws IOException {
    prop=new Properties();
    FileInputStream objfile = new FileInputStream(
            "\\resources\\config.properties");
    prop.load(objfile);
    objfile.close();
}

文件夹结构为

enter image description here

4 个答案:

答案 0 :(得分:0)

您应该将属性作为资源加载,因为它们是项目的一部分。无需使用完整的文件系统路径。

Properties prop = new Properties();

@BeforeTest
public void beforeTest() throws Exception {
  try (InputStream in = getClass().getResourceAsStream("/Config.properties") {
    prop.load(in);
  }  
}

请注意,不建议使用默认的Java包以避免类路径冲突。将Config.properties移至命名包即可解决该问题。

答案 1 :(得分:0)

您是否尝试过在调试模式下运行?好像您的prop对象为null。因此,没有什么可加载的。您需要在方法内部创建Properties对象。将构造函数移到方法内部,然后检查。

@BeforeTest
    public void beforeTest() throws IOException {
        Properties prop=new Properties();
        FileInputStream objfile = new FileInputStream(
                "C:\\Users\\psailaja\\workspace\\TestPropertiesAndKeyword\\Config.properties");
        prop.load(objfile);
        objfile.close();
    }

答案 2 :(得分:0)

尝试从属性文件获取 <div class="container"> <nav class="navbar sticky-top"> <div class="grid"> <div class="row"> <div class="col-md-4"> <a class="btn btn-primary" data-toggle="collapse" href="#collapse-top-menu" role="button" aria-expanded="false" aria-controls="collapse-top-menu"> <img src="img/baseline-menu-24px.svg"> </a> </div> <div class="col-md-8 pull-right"> <a class="navbar-brand" href="#"> <img src="img/bootstrap-solid.svg" width="40" height="40"> <span>Test</span> </a> </div> </div> <div class="row"> <div class="col-md-12"> <div class="collapse" id="collapse-top-menu"> <input type="text" class="form-control" id="input-top-collapse-search" placeholder="Cosa stai cercando?"> </div> </div> </div> </div> </nav> </div> .collapse input{ width:100%; } 时,您会得到空指针异常。您必须在这里注意以下几个事实:

  • 将属性文件的名称从properties(key:value pairs)更改为 config.properties
  • 在获取项目位置的帮助时,请通过 config.property
  • 使用参考
  • 您需要初始化对象{strong> .Properties类型。
  • 这是您的工作代码:

    prop

答案 3 :(得分:0)

感谢您的回复

该问题是由于未对从属性文件中提取的变量声明有效的访问修饰符(公共静态)而引起的。 以下几点没有问题

  • 我们可以在不使用资源文件夹的情况下声明属性文件
  • 我们可以将属性文件声明为config.properties或config.property,不需要任何专有名称
  • 通过FIS,我们可以不使用getClass()。getResourceAsStream(“ / Config.properties”)格式获取文件