[英]JUnit test for complex Java Models
我想學習/知道如何用JUnit測試復雜的Java類。
我有一個Java項目,正在從屬性文件中讀取內容,然后將文件內容解析為Java對象。 屬性文件具有樹形結構,因此我同樣實現了Java模式的復合模式。
因此,當我想為組合類或項目的任何類編寫單元測試時,應該如何編寫這些測試? 測試應該如何? 應該是這樣嗎?
@Test
public void testComposition()
{
// Create a object of the Composite class, what you expect after reading
// from the file
Composite expectedObject = new Composite();
...
// Call the parser class of the file which returns a composite
Composite createdObject = PropertiesFileParser.parse(file);
// and then i have to assert the 2 object with a method from Assert
// e.g.
assertEqual(createdObject, expectedObject);
}
我是否必須“手工”創建預期的Composite對象expectedObject
? 還是有其他方法可以做類似的事情?
編寫Junit測試用例時是否有一些編碼約定?
感謝您提供的所有有用答案! (請原諒我的英語)
首先,您應該檢查對象的每種方法。 因此,如果我是您,我將通過調用葉子和合成的個別方法來檢查一個微小模型的一些瑣碎情況。 例如,我將:
然后,您需要編寫一些測試來確保您對象的equals()
方法絕對正確地工作,因為稍后此方法將被junit的assertEqual()
大量調用。 因此,如果我是你,我會:
...等等,依此類推,直到您確信在未經測試的Leaf.equals()
和Composite.equals()
方法中絕對不會發生任何事情。
然后,您應該手工測試小型層次結構的基礎。 所以:
完成上述所有操作后,即可打磁盤。
擊打磁盤是為了確保模型的復雜實例仍然有效。 您可以編寫PropertiesFileWriter
來將層次結構寫入文件,因此可以創建對象層次結構,將其寫入文件,然后將文件讀取至另一個對象層次結構,並比較兩個對象層次結構。
要使測試非常簡單易讀,您可以創建類似以下的內容
@Test
public void testComposition()
{
// given
Composite expectedObject = getExpectedComposite();
// when
Composite createdObject = PropertiesFileParser.parse(file);
// then
assertTrue(areCompositesEquals(createdObject, expectedObject));
}
private Composite getExpectedComposite() {
Composite composite = new Composite();
// construct a composite you expect after reading from file
return composite;
}
private static boolean areCompositesEquals(Composite createdObject,
Composite expectedObject) {
// assert...
// assert...
// assert...
// list of asserts here that check the composites are equals (number of children and other condition)
return true;
}
為了避免磁盤上的I / O操作,可以為測試文件創建模擬。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.