AssertionFailedError 当输出相同时

AssertionFailedError when output is identical

预期和实际输出的内容相同,但我得到 org.opentest4j.AssertionFailedError

我试图用 System.lineSeparator() 替换所有 /n 但我得到的输出是:"contents have differences only in line separators"

  @BeforeEach
    public void setUpStreamsAndEmptyFile() {
        System.setOut(new PrintStream(outContent));
        System.setErr(new PrintStream(errContent));

        // emptying file contents
        try {
            PrintWriter pw = new PrintWriter(filePath);
            pw.close();
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        }
    }

    @AfterEach
    public void restoreStreams() {
        System.setOut(originalOut);
        System.setErr(originalErr);
    }

    @Test
    public void executeCreateEventCommand() {
        String expected = "\t Got it. I've added this task: " + System.lineSeparator() +
                "\t  [Event][✗] Project Meeting (at: 28/08/19 1600 - 28/08/19 1800)" + System.lineSeparator() +
                "\t Now you have 1 task in the list" + System.lineSeparator();

        CreateEventCommand command = new CreateEventCommand("Project Meeting /at 28/08/19 1600 - 28/08/19 1800");
        try {
            command.execute(tasks, ui, storage);
        } catch (DukeException e) {
            System.out.println("execute create event command test should pass, but it didn't " + e.getMessage());
        }

        assertEquals(expected, outContent.toString());
    }

我不会在您的预期中包含制表符或行分隔符,并且在比较之前也会在您的 outContent.toString() 中替换所有这些:

final String cleanOutput = outContent.toString().replaceAll("\n", "").replaceAll("\r", "");
assertEquals(expected, cleanOutput);

这个呢?

或许您可以尝试检查您的结果中是否有多个子字符串。您可以使用 assertThatHamcrest 来做到这一点。所以你可以避免行分隔符。

import org.hamcrest.core.StringContains;
import org.junit.Assert;

...

String expectedSubString1 = "Got it. I've added this task:"; 
String expectedSubString2 = "[Event][✗] Project Meeting (at: 28/08/19 1600 - 28/08/19 1800)";
String expectedSubString3 = "Now you have 1 task in the list";

...
String result = outContent.toString();
Assert.assertThat(result, StringContains.containsString(expectedSubString1));
Assert.assertThat(result, StringContains.containsString(expectedSubString2));
Assert.assertThat(result, StringContains.containsString(expectedSubString3));

你这里的问题是一个更大问题的征兆。这只是一个完美的例子,说明了为什么你基本上不应该对复杂的字符串断言。更多地关注围绕任务是否正确创建的测试,而不是您向用户显示的消息。这很容易改变太频繁的方式来断言它。

想一想当测试返回失败时您希望它意味着什么。