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 [email protected]/org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
    at [email protected]/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.

1 Answer 1

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());
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, it works fine with lineSeparator(). I did not know line separator is different on Windows. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.