0

I am testing a simple helloWorld class.

package Codewars;

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World");
    }

}

And I have a test class as follows (based on the answer ):

import static org.junit.jupiter.api.Assertions.*;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class helloWorldTest {

    private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    private final PrintStream originalOut = System.out;

    @BeforeEach
    public void setUpStreams() {
        System.setOut(new PrintStream(outContent));
    }

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

    @Test
    void test() {
        HelloWorld.main(null);
        assertEquals("Hello World\n", outContent.toString());
    }

}

It results in failure with error message as follows:

org.opentest4j.AssertionFailedError: expected: <Hello World
> but was: <Hello World
>
    at org.junit.jupiter.api@5.5.1/org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
    at org.junit.jupiter.api@5.5.1/org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
    ...

It seems like the strings are same and still the error is thrown?

Thank you in advance.

Vintux
  • 43
  • 7

1 Answers1

3

Make sure that your line separator is equal to \n on your system. This is not the case on Windows.

To fix the test, modify it to take system-specific separator into account

assertEquals("Hello World" + System.lineSeparator(), outContent.toString());
Lesiak
  • 22,088
  • 2
  • 41
  • 65
  • Yeah, it works fine with lineSeparator(). I did not know line separator is different on Windows. Thanks – Vintux Feb 21 '20 at 10:23