smanvi12
smanvi12

Reputation: 581

JUnit test for System.out.println/System.err.println

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[
]
>

Upvotes: 2

Views: 1519

Answers (1)

Jens
Jens

Reputation: 69440

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());

Upvotes: 3

Related Questions