Java:测试包括“换行"在内的系统输出.与assertEquals [英] Java: test System output including "new lines" with assertEquals

查看:99
本文介绍了Java:测试包括“换行"在内的系统输出.与assertEquals的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为策略设计模式编写单元测试.我正在使用assertEquals方法将System输出与字符串进行比较.输出看起来相同,但是我的测试一直失败.我以为我忘记了与换行或制表符有关的内容?

I'm currently writing a Unit Test for the Strategy Design Pattern. I'm comparing the System output with a string in the assertEquals method.The output looks the same but my test keeps failing.. . I'm thinking that I'm forgetting something to do with new lines or tabs?

我的单元测试:

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;

public class MiniDuck1Test {

    private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();

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

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

    @Test
    public void testDuck1() {       
        Duck mallard = new MallardDuck();
        mallard.performQuack();
        mallard.performFly();

        Duck model = new ModelDuck();
        model.performFly();
        model.setFlyBehavior(new FlyRocketPowered());
        model.performFly();

        assertEquals("Quack\nI'm flying!!\nI can't fly\nI'm flying with a rocket", outContent.toString().trim());
    }
}

输出(第二行和第三行显示为红色):

Output (second and third line appear red):

Quack
I'm flying!!
I can't fly
I'm flying with a rocket

最快的解决方案似乎是在我的"\ n"前面添加一个"\ r".多个答案告诉我,对于Windows,这需要完成.应用后,我的assertEquals看起来像:

The quickest solution seemed to be adding an "\r" in front of my "\n". Multiple answers informed me that this needs to be done for Windows. After applying this my assertEquals looked like:

assertEquals("Quack\r\nI'm flying!!\r\nI can't fly\r\nI'm flying with a rocket", outContent.toString().trim());

也:我忘了提到大部分代码来自本书:Eric Freeman,Elisabeth Robson,Bert Bates和Kathy Sierra的"Head First Design Patterns".

Also: I forgot to mention that most of the code came from the book: "Head First Design Patterns" by Eric Freeman, Elisabeth Robson, Bert Bates and Kathy Sierra.

推荐答案

如果您正在寻找与平台无关的方法,除了其他答案...

In addition to the other answers if you are looking for a platform-independent way...

一种独立于平台的快速解决方案可以替换行分隔符

A quick platform-independent solution can be to replace the line separators

String expected = "Quack\nI'm flying!!\nI can't fly\nI'm flying with a rocket"
                       .replaceAll("\\n|\\r\\n", System.getProperty("line.separator"));
assertEquals(expected, outContent.toString().trim());

或使用PrintWriter生成预期的字符串.

or using a PrintWriter to build the expected string.

StringWriter expectedStringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(expectedStringWriter);

printWriter.println("Quack");
printWriter.println("I'm flying!!");
printWriter.println("I can't fly");
printWriter.println("I'm flying with a rocket");
printWriter.close();

String expected = expectedStringWriter.toString();
assertEquals(expected, outContent.toString());

或创建自己的断言类以重用它

or create an own assert class to re-use it

class MyAssert {

    public static void assertLinesEqual(String expectedString, String actualString){
        BufferedReader expectedLinesReader = new BufferedReader(new StringReader(expectedString));
        BufferedReader actualLinesReader = new BufferedReader(new StringReader(actualString));

        try {
            int lineNumber = 0;

            String actualLine;
            while((actualLine = actualLinesReader.readLine()) != null){
                String expectedLine = expectedLinesReader.readLine();
                Assert.assertEquals("Line " + lineNumber, expectedLine, actualLine);
                lineNumber++;
            }

            if(expectedLinesReader.readLine() != null){
                Assert.fail("Actual string does not contain all expected lines");
            }
        } catch (IOException e) {
            Assert.fail(e.getMessage());
        } finally {
            try {
                expectedLinesReader.close();
            } catch (IOException e) {
                Assert.fail(e.getMessage());
            }
            try {
                actualLinesReader.close();
            } catch (IOException e) {
                Assert.fail(e.getMessage());
            }
        }
    }
}

然后,如果测试失败,则可以提供更好的问题描述.例如

Then you can give a better problem description if the test fails. E.g.

MyAssert.assertLinesEqual(
         "Quack\nI'm flying!!\nI can not fly\nI'm flying with a rocket\n",
         outContent.toString());

将输出

org.junit.ComparisonFailure: Line 2 
Expected :I can not fly
Actual   :I can't fly

这篇关于Java:测试包括“换行"在内的系统输出.与assertEquals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆