-1

I'm trying to check console output by redirecting the standard output to a ByteArrayOutputStream object. I found this little code snipped that lets me do just that. However, usage of characters such as "-","+" etc. fail the tests. I was wondering why:

Here's the jUnit Test:

import static org.junit.Assert.*;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

//This test is try and test output against the console output,
//but the inclusion of characters '-', '*', '+', and '/' makes
//it especially hard to implement correctly. So abandoning
public class ApplicationTest {
    private final ByteArrayOutputStream outContent=new ByteArrayOutputStream();

    @Before
    public void setUpStreams(){
        System.setOut(new PrintStream(outContent));     
    }

    @After
    public void cleanUpStream(){
        System.setOut(null);
    }

    @Test
    public void test_Test1() {
        //Lexer lex=new Lexer("a+b*c");
        //System.out.print("a b c * + ");
        System.out.format("%s ", "a");
        System.out.format("%s ", "- ");
        String str="a - ";      

                //Test Fails.                       
        assertEquals(outContent.toString(),str);
    }

}
apil.tamang
  • 2,545
  • 7
  • 29
  • 40
  • 1
    If you want our help, then post the very explanatory error message that JUnit gives you. – chrylis -cautiouslyoptimistic- Feb 22 '14 at 21:02
  • Just a note: calling System.setOut(null) doesn't reset System.out to its default value. You should keep a reference to the original System.out before changing is, and set it back to this reference. – JB Nizet Feb 22 '14 at 21:14

1 Answers1

5

You have an extra space in the output.

System.out.format("%s ", "a");
System.out.format("%s ", "- ");
//                         ^
String str="a - ";      
Kevin
  • 53,822
  • 15
  • 101
  • 132
  • 1
    Boy you have to read that several times, don't you. It's "a - " when formatted. Two spaces after the "-" -- one from the "%s " format and one from the "- " string literal. – Hot Licks Feb 22 '14 at 21:11
  • The problem could have been fairly easily diagnosed by simply printing the two strings and (carefully) observing the difference. – Hot Licks Feb 22 '14 at 21:14
  • @hotlicks I always print with surrounding square brackets so i can clearly see leading/trailing whitespace, especially trailing newlines. – Bohemian Feb 22 '14 at 21:16
  • 1
    @Bohemian - Always something -- I kinda like ">>>..<<<". (Hard to believe a Bohemian would use *square* brackets!!) – Hot Licks Feb 22 '14 at 21:19
  • gotcha, that was a remnant from something else, and I became convinced after a while that these characters somehow got encoded differently in the output stream. – apil.tamang Feb 22 '14 at 21:30
  • @apil.tamang - As a general rule, when you think the compiler or runtime support or whatever is "broken", you're wrong. – Hot Licks Feb 23 '14 at 01:31