English 中文(简体)
使用Junit比较文本文件
原标题:
  • 时间:2009-01-21 20:27:26
  •  标签:

我正在使用Junit比较文本文件:

public static void assertReaders(BufferedReader expected,
          BufferedReader actual) throws IOException {
    String line;
    while ((line = expected.readLine()) != null) {
        assertEquals(line, actual.readLine());
    }

    assertNull("Actual had more lines then the expected.", actual.readLine());
    assertNull("Expected had more lines then the actual.", expected.readLine());
}

这是比较文本文件的好方法吗? 有没有更好的选择?

最佳回答

junit-addons有很好的支持:FileAssert

它会给你一些异常,例如:

junitx.framework.ComparisonFailure: aa Line [3] expected: [b] but was:[a]
问题回答

这里是一个简单的方法来检查文件是否完全相同

assertEquals("The files differ!", 
    FileUtils.readFileToString(file1, "utf-8"), 
    FileUtils.readFileToString(file2, "utf-8"));

其中file1file2File实例,FileUtils来自Apache Commons IO

没有太多自己的代码需要维护,这始终是个好处。 :) 如果您已经在项目中使用Apache Commons,那么非常容易。但是没有像mark s解决方案那样的漂亮的详细错误信息。

Edit:
Heh, looking closer at the FileUtils API, there s an even simpler way:

assertTrue("The files differ!", FileUtils.contentEquals(file1, file2));

作为额外的奖励,这个版本适用于全部文件,不仅限于文本。

截至2015年,我会推荐使用AssertJ,这是一种优雅而全面的断言库。对于文件,您可以对比另一个文件进行断言。

@Test
public void file() {
    File actualFile = new File("actual.txt");
    File expectedFile = new File("expected.txt");
    assertThat(actualFile).hasSameTextualContentAs(expectedFile);
}

或反对内联字符串:

@Test
public void inline() {
    File actualFile = new File("actual.txt");
    assertThat(linesOf(actualFile)).containsExactly(
            "foo 1",
            "foo 2",
            "foo 3"
    );
}

故障信息也非常详细。如果一行不同,您会收到:

java.lang.AssertionError: 
File:
  <actual.txt>
and file:
  <expected.txt>
do not have equal content:
line:<2>, 
Expected :foo 2
Actual   :foo 20

如果其中一个文件有更多的行,你就会得到:

java.lang.AssertionError:
File:
  <actual.txt>
and file:
  <expected.txt>
do not have equal content:
line:<4>,
Expected :EOF
Actual   :foo 4

使用 java.nio.file API对两个文件内容进行简单比较。

byte[] file1Bytes = Files.readAllBytes(Paths.get("Path to File 1"));
byte[] file2Bytes = Files.readAllBytes(Paths.get("Path to File 2"));

String file1 = new String(file1Bytes, StandardCharsets.UTF_8);
String file2 = new String(file2Bytes, StandardCharsets.UTF_8);

assertEquals("The content in the strings should match", file1, file2);

或者如果您想比较单独的行:

List<String> file1 = Files.readAllLines(Paths.get("Path to File 1"));
List<String> file2 = Files.readAllLines(Paths.get("Path to File 2"));

assertEquals(file1.size(), file2.size());

for(int i = 0; i < file1.size(); i++) {
   System.out.println("Comparing line: " + i)
   assertEquals(file1.get(i), file2.get(i));
}

我建议使用Assert.assertThat和一个hamcrest匹配器(junit 4.5或更高版本-甚至是4.4)。

我最后得到的是类似于:

assertThat(fileUnderTest, containsExactText(expectedFile));

我的匹配者在哪里:

class FileMatcher {
   static Matcher<File> containsExactText(File expectedFile){
      return new TypeSafeMatcher<File>(){
         String failure;
         public boolean matchesSafely(File underTest){
            //create readers for each/convert to strings
            //Your implementation here, something like:
              String line;
              while ((line = expected.readLine()) != null) {
                 Matcher<?> equalsMatcher = CoreMatchers.equalTo(line);
                 String actualLine = actual.readLine();
                 if (!equalsMatcher.matches(actualLine){
                    failure = equalsMatcher.describeFailure(actualLine);
                    return false;
                 }
              }
              //record failures for uneven lines
         }

         public String describeFailure(File underTest);
             return failure;
         }
      }
   }
}

配对专业人员:

  • Composition and reuse
  • Use in normal code as well as test
    • Collections
    • Used in mock framework(s)
    • Can be used a general predicate function
  • Really nice log-ability
  • Can be combined with other matchers and descriptions and failure descriptions are accurate and precise

缺点:

  • Well it s pretty obvious right? This is way more verbose than assert or junitx (for this particular case)
  • You ll probably need to include the hamcrest libs to get the most benefit

FileUtils 确实是一个很好的工具。这里还有另一种简单方法来检查文件是否完全相同。

assertEquals(FileUtils.checksumCRC32(file1), FileUtils.checksumCRC32(file2));

虽然assertEquals()提供的反馈略多于assertTrue(),但checksumCRC32()函数的结果是一个长整型,所以可能没有什么内在的帮助。

如果预期比实际多行,那么在执行assertNull之前将会失败于assertEquals。

虽然很容易修复:

public static void assertReaders(BufferedReader expected,
    BufferedReader actual) throws IOException {
  String expectedLine;
  while ((expectedLine = expected.readLine()) != null) {
    String actualLine = actual.readLine();
    assertNotNull("Expected had more lines then the actual.", actualLine);
    assertEquals(expectedLine, actualLine);
  }
  assertNull("Actual had more lines then the expected.", actual.readLine());
}

这是我自己实现的equalFiles,您的项目无需添加任何库。

private static boolean equalFiles(String expectedFileName,
        String resultFileName) {
    boolean equal;
    BufferedReader bExp;
    BufferedReader bRes;
    String expLine ;
    String resLine ;

    equal = false;
    bExp = null ;
    bRes = null ;

    try {
        bExp = new BufferedReader(new FileReader(expectedFileName));
        bRes = new BufferedReader(new FileReader(resultFileName));

        if ((bExp != null) && (bRes != null)) {
            expLine = bExp.readLine() ;
            resLine = bRes.readLine() ;

            equal = ((expLine == null) && (resLine == null)) || ((expLine != null) && expLine.equals(resLine)) ;

            while(equal && expLine != null)
            {
                expLine = bExp.readLine() ;
                resLine = bRes.readLine() ; 
                equal = expLine.equals(resLine) ;
            }
        }
    } catch (Exception e) {

    } finally {
        try {
            if (bExp != null) {
                bExp.close();
            }
            if (bRes != null) {
                bRes.close();
            }
        } catch (Exception e) {
        }

    }

    return equal;

}

而且要使用它,只需使用常规的AssertTrue JUnit方法。

assertTrue(equalFiles(expected, output)) ;




相关问题
热门标签