使用assertEquals()对控制台println()输出进行判断失败的原因及处理

  最近在学习中遇到个小问题,但很奇怪,通过IntelliJ IDEA的人性化功能帮我发现了原因。

  主要想对比一段控制台的输出和预期是否相等。控制台输出的类代码如下,是一个使用println()进行输出的函数:

public class Chicken implements Animal {
    @Override
    public void say() {
        System.out.println("I'm a chicken!");
    }
}

  测试类如下:

import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.SystemOutRule;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AnimalConfig.class)
@ActiveProfiles("chicken")
public class Tester {
    @Rule
    /*SystemOutRule,该规则能够基于控制台的输出编写断言。*/
    public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();

    @Autowired
    private Animal animal;

    @Test
    public void testAnimal() {
        assertNotNull(animal);
        animal.say();
        assertEquals("I'm a chicken!\n", systemOutRule.getLog());
    }
}

  注意最后那句就是对比的断言了。我在预期输出最后加了个\n,对应的就是println的那个回车了,但运行死活不对!看见IDEA的控制台输出如下:


  于是点击“Click to see difference”去see一下difference:


  嗯,得亏哥之前做过基于Linux的C开发,改成"\r\n"一试,果然好了!IDEA真心赞!


  小小的记录而已……反正也没人看 -_-!!

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值