![](/img/trans.png)
[英]How to compare the contents of two text files and return “Same Content” or “Different Content”?
[英]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.