user1778824
user1778824

Reputation: 369

Reason for assertEquals() failing

The assertEquals() fails even though the both the strings are same...can someone help me figure out why?

 public void testSet() 
 {
    ByteArrayOutputStream outContent = new ByteArrayOutputStream();

    System.setOut(new PrintStream(outContent));

    instance.get();

    String output = outContent.toString();
    String input="i=1\r\n";
    assertEquals(input,output);
 }

 get()
 {
    int i=1;
    System.out.println("i="+i);
 }

Upvotes: 2

Views: 2811

Answers (1)

Yogendra Singh
Yogendra Singh

Reputation: 34367

You are using newline in your print statement in your get() method which is appending \r\n in the output buffer. This way you are getting `output = "i=1\r\n" which is not equal to "i=1".

Use the print without newline i.e. print() as below:

 System.out.print("i="+i);

If you don't want to use print() method then truncate the \r\n from the output as below:

    String output = outContent.toString();
    output = output.replaceAll("\r\n", "");
    String input="i=1";
    assertEquals(input,output);

Upvotes: 4

Related Questions