2

I have to write tests for an application and Im trying to write a juint test for somthing that is printed on the console. The application has -->

System.err.println("Username cannot be empty");

This is what I have done so far :

ByteArrayOutputStream errContent = new ByteArrayOutputStream();
System.setErr(new PrintStream(errContent));
//left username empty and pressed login
assertEquals("Username cannot be empty", errContent.toString());

But I get ComparisonFailure

expected <Username cannot be empty[]> 
but was <Username cannot be empty[
]>

//difference of next line. 

Anyone know how to solve this ? Thanks.

EDIT : Tried assertEquals("Username cannot be empty\n", errContent.toString());

Now I get :

expected <Username cannot be empty[]
> 
but was <Username cannot be empty[
]
>
kryger
  • 12,906
  • 8
  • 44
  • 65
smanvi12
  • 571
  • 8
  • 24
  • 5
    The real question is why you are testing java standard library methods at all. IMO a test shouldn't fail because someone decides to change an error message. – Sinkingpoint Mar 09 '16 at 10:08
  • What you are missing in your test is, that `System.err.println()` has a linefeed at the end. Change `assertEquals("Username cannot be empty", errContent.toString());` to `assertEquals("Username cannot be empty\n", errContent.toString());` – Jens Mar 09 '16 at 10:13
  • @Quirliom We dont at work, But this is for a class I'm taking and the application is given to us with console outputs to make tests for. – smanvi12 Mar 09 '16 at 10:15
  • @sakshik12 You could have a look at [System Rules](http://stefanbirkner.github.io/system-rules/) which helps you testing such output. Disclaimer: I'm the author of that library. – Stefan Birkner Mar 09 '16 at 22:25

1 Answers1

3

What you are missing in your test is, that System.err.println() has a linefeed at the end. Change assertEquals("Username cannot be empty", errContent.toString()); to assertEquals("Username cannot be empty"+System.getProperty("line.separator"), errContent.toString());

Jens
  • 67,715
  • 15
  • 98
  • 113