gpt4 book ai didi

java - 检查文件中是否存在某条记录

转载 作者:行者123 更新时间:2023-11-30 07:04:44 25 4
gpt4 key购买 nike

我是新手。我正在进行 JUnit 测试。这是我正在测试的内容:我有一个包含记录列表的输入文件。如果记录有电子邮件,我必须将其添加到名为 myemailfile.txt 的输出文件中

在我的 JUnit 测试中,我必须测试 email=testEmail@gmail.com 的人是否包含在 myemailfile.txt 中

有人可以建议如何浏览文件并检查此类记录是否已写入文件。

Here is my file:

First Name,Last Name,Email,Id
John ,Dough ,johnsemail@gmail.com ,12345
Jane ,Smith ,mytestemail@gmail.com ,86547
Mary ,Wells ,johnsemail@gmail.com ,76543

下面是我的测试

@Test
public void isRecordIncludedInEmailFile() throws IOException{

String testFile = "C:/Users/myname/myemailfile.txt";
BufferedReader br = null;
String line = "";
String fileSplitBy = ",";

try {

br = new BufferedReader(new FileReader(testFile));
while ((line = br.readLine()) != null) {

// use comma as separator
String[] field = line.split(fileSplitBy);

//read through the file and see if the email that I expect (testEmail@gmail.com) exists in the file
System.out.println("Email [email= " + field[2] + " , first name=" + field[0] + "]");

//the line below should assert if "testEmail@gmail.com" exists in the file
// assertEquals("testEmail@gmail.com", field[2]);
}

谢谢

最佳答案

您似乎错过了单元测试的关键点:您使用它们来测试您的java类;并不是某些文件包含某些内容。

换句话说,这里合理的做法是:

  1. 创建一个代表此类记录的,可能称为PersonInformation
  2. 编写代码来读取此类文件,并将文件内容转换为PersonInformation对象的某个数组或列表
  3. 然后编写一个单元测试,创建一个包含一些数据的伪造文件;您运行代码...并测试是否找到、读入并存储了该列表中所需的 PersonInformation 对象。

最后提示:除非这是一个“学习练习”,否则您不想想要手动解析该文件内容。您会看到,该数据使用 CSV 格式(逗号分隔值)。编写代码来读取此类数据并解析它......意味着重新发明轮子。有很多库可以为您完成这项工作。

关于java - 检查文件中是否存在某条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40337133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com