我目前正在爲策略設計模式編寫單元測試。我將系統輸出與assertEquals方法中的一個字符串進行比較。輸出看起來相同,但我的測試仍然失敗。我在想我忘記了一些新的行或標籤?Java:測試包括「新行」與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
編輯:
最快的解決辦法似乎是增加一個「\ r「在我的」\ n「前面。多個答案告訴我這需要在Windows上完成。應用在這之後我的assertEquals樣子:
assertEquals("Quack\r\nI'm flying!!\r\nI can't fly\r\nI'm flying with a rocket", outContent.toString().trim());
另外:我忘了提,大部分代碼都來自書:「Head First設計模式」,由埃裏克·弗里曼,伊麗莎白·羅布森,伯特·貝茨和凱西塞拉利昂。
而不是'Assert.equals()','TestCase.equals()'在顯示不匹配字符串的錯誤位置做了很好的工作。只需相應地編輯您的進口報表。 –
嘗試比較字符串的長度。有些人認爲這可能是'\ r \ n',或者是其他一些無形的差異。 – shmosel