我正在为几乎没有Java知识的Android应用程序创建自动化测试。我正在使用测试记录器生成基本的robotium脚本,然后手动更新它们。测试工作正常,脚本中硬编码的登录凭据,但要将这些测试应用于多个帐户,我想从文本文件中读取用户名和密码。扫描器实例在我看来是一种逻辑方法,用于将文本文件中的行分隔字符串读入登录凭据的变量,但是我无法确定将代码放在何处。似乎无论我尝试什么变量都超出了范围(没有被使用)或者我想出了一些例外或其他。
这是我正在使用的扫描程序代码,目前位于测试代码的顶部:
public void testRecorded() throws Exception {
String userName;
String passWord;
Scanner scanFile = null;
try {
scanFile = new Scanner("C:/...path to file...file.txt");
//Read the password from file
userName = scanFile.nextLine();
//Consume the line break
scanFile.nextLine();
//Read the password from file
passWord = scanFile.nextLine();
}
finally {
scanFile.close();
}
Test code continues...
在我使用NoSuchElementException消耗换行符的nextLine语句中运行它失败
Scanner是用于从文本文件中读取用户名和密码的最佳方法吗?我的扫描仪代码有问题吗?我在哪里将Scanner代码放入测试中?它是否需要单独的类,或者我可以将此代码与我的其他测试代码保持一致吗?
答案 0 :(得分:0)
您想要从主机扫描文件(“C:/ ...”)。设备无权访问。您必须将文件放到设备上,例如在SD卡上。
如果要使用扫描仪扫描文件,则无法在其中传递字符串。你应该使用:
// if you put file.txt directly on sdcard (/sdcard/file.txt)
String path = String.format("%s/%s", Environment.getExternalStorageDirectory(), "file.txt");
Scanner scan = new Scanner(new File(path));
...