简体   繁体   English

用于测试 system.out.println 结果的 JUnit 测试失败

[英]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我有一个简单的函数countUpDown(0, 3)需要打印一些这样的结果: 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:但是,当我进行 JUnit 测试时,它会像这样失败:

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.println 将在您传递的值后向字符串添加一个换行符“\\n”。 System.out.print does not add the line feed character System.out.print 不添加换行符

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.由于 jUnit 报告测试失败,因为预期的字符串(测试中的字符串)在末尾没有像实际字符串(来自 outContent 的字符串)那样的换行符。

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:我不确定您的代码是否正确,您可以修改为使用 print 而不是 println 但随后以下测试将无法通过:

@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.实际上取决于您要完成的任务,但是在 outContent.toString() 的结果上设置一些断点应该是有益的。

The expected output string that you are trying to assert should be您尝试断言的预期输出字符串应该是

0\\n1\\n0\\n 0\\n1\\n0\\n

as there is a println.因为有一个 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());
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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