简体   繁体   中英

JUnit test failed for testing system.out.println result

I have a simple function countUpDown(0, 3) that needs to print some results like this: 0,1,2,3,2,1,0

  class CountNumP2{
    public void countUpDown(int start, int end) {
            System.out.println(start);
            if (start >= end) {
                return;
            }
            countUpDown(start + 1, end);
            System.out.println(start);
        }
   }

My function should work fine. However, when I did a JUnit test it fails like this:

import static org.junit.Assert.*;

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

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

public class CountNumP2Test {

    private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();

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

    @Test
    public void test() {
        CountNumP2 cn = new CountNumP2();
        cn.countUpDown(0, 1);
        String output =  0 + "\n" + 1 + "\n" + 0;
        assertEquals(output , outContent.toString());
    }

}

I think my test should pass, does anyone know the problem? Thank you so much

System.out.println will add a line feed character "\\n" to the string after the value you pass it. System.out.print does not add the line feed character

As jUnit reports the test fails because of the expected string (the one in the test) doesn't have a line feed at the end like the actual string (the one from outContent) does.

I'm not sure if your code is correct or not, you could modify to use print instead of println but then the following test won't pass:

@Test
public void testMoreThenOneOff() {
    CountNumP2 cn = new CountNumP2();
    cn.countUpDown(0, 2);
    String output = "0\n1\n2\n1\n0";
    assertEquals(output , outContent.toString());
}

Really depends on what you are trying to accomplish, but setting some breakpoints on the result of the outContent.toString() should be beneficial.

The expected output string that you are trying to assert should be

0\\n1\\n0\\n

as there is a println.

Corrected unit test method should be as below.

    @Test
    public void test() {
        CountNumP2 cn = new CountNumP2();
        cn.countUpDown(0, 1);
        String output =  "0\n1\n0\n";
        Assert.assertEquals(output , outContent.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