简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM