I have been trying JUnit for the first time and I am facing a strange error:
Tests on method are okay, but when I tried my first test in the main method, it fails without reason. This is the code for the test:
@Test
public void MyTestMain1(){
String input = "1\n2\n2\n";
ByteArrayInputStream in = new ByteArrayInputStream(input.getBytes());
System.setIn(in);
ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
String [] args = {};
Demo.main(args);
// expected output:
String consoleOutput = "Enter side 1: \n";
consoleOutput += "Enter side 2: \n";
consoleOutput += "Enter side 3: \n";
consoleOutput += "This is a triangle.\n";
assertEquals(consoleOutput, out.toString());
}
And here the code of my main class:
public class Demo {
public static void main(String[] args) {
// Reading from System.in
Scanner reader = new Scanner(System.in);
System.out.println("Enter side 1: ");
// Scans the next token of the input as an int.
int side_1 = reader.nextInt();
System.out.println("Enter side 2: ");
// Scans the next token of the input as an int.
int side_2 = reader.nextInt();
System.out.println("Enter side 3: ");
// Scans the next token of the input as an int.
int side_3 = reader.nextInt();
if (isTriangle(side_1, side_2, side_3)) {
System.out.println("This is a triangle.");
}
else {
System.out.println("This is not a triangle.");
}
reader.close();
}
public static boolean isTriangle(double a, double b, double c) {
if ((a + b > c) &&
(a + c > b) && // should be a + c > b
(b + c > a)) {
return true;
}
return false;
}
}
It is very simple, but it is failing and the reason is some strange hidden character that I don't know where is coming from.
Here is the output by JUnit:
And here what I see if I double click on it:
In the first image it appears to be an additional "\n" but in the second one it doesn't appear. Also, if I add it manually then the same error will appear, though now the second image will be the one showing that there is an additional \n.
Line seperators are platform dependant. For example, For Windows, Line Separator means \r\n
\r - carriage return
\n - new line
The problem is that the expected String has \n only while when the String gets generated using Scanner, it has \r\n. Due to this both strings were not equal.
To solve this issue, you can add platform independent line separator through
System.lineSeparator()
Using this will ensure, the code doesn't break in other operating systems.