目前正在学习自动化测试,我不明白我的代码有什么问题。我正在尝试从.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
这是我的文件的体系结构:architecture
ps我正在尝试从测试中获取源文件-> LabelsAndFoldersTest.java
您提供的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);
如果您的文件位于资源目录中,那么我想它将被打包到jar文件中。因此,更好的方法是使用此代码加载资源
// if config.properties located in root of resources
InputStream io = YourClassName.class.getClassLoader().getResourceAsStream("config.properties");
Properties props = new Properties()
props.load(io)
使用ClassLoader加载文件要容易得多。使用getClass()。getResourceAsStream()来获取类路径中的文件:
InputStream is = youClassName.class.getResourceAsStream("/full/path/config.properties");
if(is != null) {
Properties adminProps = new Properties();
adminProps.load(is);
请注意,斜杠非常重要。