簡體   English   中英

JUnit:比較兩個無序文本文件的內容

[英]JUnit: compare the contents of two unordered text files

我想編寫一個單元測試,以將方法的文本文件輸出與期望值進行比較。 但是,我不希望在比較中將測試限制為具有精確的行順序要求。 是否有一種優雅的方法可以用Java / Junit編寫這樣的測試,或者我必須為此任務編寫自己的邏輯?

謝謝!

Setjmp

我建議您將被測方法的返回值和期望值轉換為兩個字符串列表,每行一個字符串。

然后可以使用AssertJ輕松比較這兩個列表。 在測試列表上的斷言時,我發現它是一個很好的工具:

@Test
public void shouldContainSameLines() throws IOException {
  List<String> actualLines = ClassUnderTest.loadText();

  List<String> expectedLines = asList("Hello", "World", "Goodbye");
  assertThat(actualLines)
      .containsAll(expectedLines);
}

assertThat()是AssertJ的流暢API的入口點。 根據傳遞給assertThat()的方法的類型,提供了明智的驗證。 在這種情況下,我使用containsAll()來測試actualLines包含所有按expectedLines順序排列在expectedLines中的行。

為此,您可以使用org.hamcrest.Matchers.containsInAnyOrder(T... items)

@Test
public void testSomeMethod_shouldReadFileProperly() {
    String contents = "foo\nbar"; // change to actual method call
    assertThat(Arrays.asList(contents.split("\n"), 
            containsInAnyOrder("bar", "foo"));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM