【问题标题】:Check if a certain record is in the file检查某个记录是否在文件中
【发布时间】:2025-12-23 21:30:10
【问题描述】:

我是新手。我正在做一个 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 junit io bufferedreader filereader


    【解决方案1】:

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

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

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

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

    【讨论】: