您的位置:首页 > 其它

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

2017-10-19 22:42 363 查看
  最近在学习中遇到个小问题,但很奇怪,通过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真心赞!



  小小的记录而已……反正也没人看 -_-!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐