我目前正在为战略设计模式编写单元测试.我正在将系统输出与assertEquals方法中的字符串进行比较.输出看起来相同但我的测试仍然失败... 我在想我忘记了与新线或标签有关的事情?
我的单元测试:
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()); } }
输出(第二行和第三行显示为红色):
Quack I'm flying!! I can't fly I'm flying with a rocket
编辑:
最快的解决方案似乎是在我的"\n"前添加一个"\ r".多个答案告诉我,这需要在Windows上完成.应用此之后,我的assertEquals看起来像:
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".