2016-03-17 48 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"); 
    } 
} 
相关问题