2016-03-17 51 views
0

這裏是我的測試:失敗的assertEquals兩個看似相同的字符串

@Test 
public void testAddPaperConfirm() 
{ 
    String input = "P\n" + 
        "The Life of Geoff the Platypus"; 
    InputStream testInput = new ByteArrayInputStream(input.getBytes()); 
    System.setOut(new PrintStream(testOutput)); 
    System.setIn(testInput); 
    testReviewSystem.main(new String[] {}); 
    assertEquals(testOutput.toString(), "What do you want to do?\n" + 
      "O = Overview, P = Add Paper, R = Add Review, [num] = Detail of that paper, X = exit\n" + 
      "What is the title of the paper?\n" + 
      "[Paper added]\n" 
      + "What do you want to do?\n" + 
      "O = Overview, P = Add Paper, R = Add Review, [num] = Detail of that paper, X = exit\n"); 
} 

當我看到這兩個字符串有人告訴我他們是相同的。 enter image description here

+1

提示:遠離assertEquals。只要看看它的大哥** assertThat **。比較價值和告訴你什麼是不匹配通常會更好。 – GhostCat

+1

您的測試缺少一些可以讓我們嘗試重現問題的重要信息。您是否可以更新以包含它? – Krease

+2

也許實際輸出使用'\ r \ n'換行符? – Andreas

回答

0

這是失敗的,因爲它們不相同。

看起來相同的兩個字符串可能不同。有很多字節無法表示和顯示。

例如ascii碼0和ascii碼1,他們看起來相同,但他們不是。

http://www.ascii-code.com/

0

我認爲你在Windows上運行測試,並將其輸出\r\n代替\n作爲行分隔符。您可以通過將您的斷言更改爲以下代碼來嘗試此操作。

assertEquals(testOutput.toString(), "What do you want to do?\r\n" + 
     "O = Overview, P = Add Paper, R = Add Review, [num] = Detail of that paper, X = exit\r\n" + 
     "What is the title of the paper?\r\n" + 
     "[Paper added]\r\n" 
     + "What do you want to do?\r\n" + 
     "O = Overview, P = Add Paper, R = Add Review, [num] = Detail of that paper, X = exit\r\n") 

我寫了一個名爲System Rules測試庫,使測試命令行應用程序更加容易。

public class TheTest { 
    @Rule 
    public final TextFromStandardInputStream systemInMock 
    = emptyStandardInputStream(); 
    @Rule 
    public final SystemOutRule systemOutRule 
    = new SystemOutRule().enableLog(); 

    @Test 
    public void testAddPaperConfirm() { 
    systemInMock.provideLines("P", "The Life of Geoff the Platypus"); 
    testReviewSystem.main(new String[] {}); 
    String output = systemOutRule.getLogWithNormalizedLineSeparator(); 
    assertEquals(output, "What do you want to do?\n" + 
     "O = Overview, P = Add Paper, R = Add Review, [num] = Detail of that paper, X = exit\n" + 
     "What is the title of the paper?\n" + 
     "[Paper added]\n" 
     + "What do you want to do?\n" + 
     "O = Overview, P = Add Paper, R = Add Review, [num] = Detail of that paper, X = exit\n"); 
    } 
} 
相關問題