属性文件值未出现在我的变量中

Properies file values doesn't appear in my variable

目前正在学习自动化测试,我无法理解我的代码有什么问题。我正在尝试从 .properties 文件中获取信息并将其用作变量。我收到一个错误:

java.io.FileNotFoundException: ..\resources\config.properties (The system cannot find the path specified)

但是,我确信我的道路是正确的。尝试了不同的变体,如 //resources//config...,甚至 \,仍然是同样的问题。

这是我尝试从 config.properties 文件获取信息的代码:

@Test
public void myFirstTest() {
        LoginPage log = new LoginPage();

        try(FileReader reader = new FileReader("../resources/config.properties")) {
            Properties properties = new Properties();
            properties.load(reader);
            String username = (String) properties.get("username");
            String password = (String) properties.get("password");
            System.out.println("h" + username);
            log.insertUsername(username);
            log.insertPassword(password);
        } catch(Exception e) {
            e.printStackTrace();
        }
}

这就是我的样子 config.properties

username = myUserName1
password = myTestPass1

这是我文件的架构:

P.S。我正在尝试从测试中获取源文件 -> LabelsAndFoldersTest.java

使用类加载器加载文件要容易得多。使用 getClass().getResourceAsStream() 获取类路径中的文件:

InputStream is = youClassName.class.getResourceAsStream("/full/path/config.properties");
if(is != null) {
    Properties adminProps = new Properties();
    adminProps.load(is);

请注意,前导斜线非常重要。

您提供的 config.properties 路径不正确

我可以看到你项目结构的图像,你的项目下有一个 src/resources 文件夹,那里有地方 config.properties

将文件路径更改为src/resources/config.properties

try(FileReader reader = new FileReader("src/resources/config.properties"))

好吧,问题是您指定了相对文件路径。这取决于 System.property("user.dir")

要弄清楚它的价值,只需打印它即可。

String currentDirectory = System.getProperty("user.dir");
System.out.println("The current working directory is " + currentDirectory);

如果你的文件在resources目录下,估计会被打包成jar文件。所以更好的方法是用这段代码加载资源

// if config.properties located in root of resources
InputStream io = YourClassName.class.getClassLoader().getResourceAsStream("config.properties");
Properties props = new Properties()
props.load(io)