2013-10-31 131 views
0

這些是我現在要測試的方法。如何在JUnit測試用例中測試方法中的方法?

public void addGrade(String newGrade) { 
    if (numGrades >= grades.length) { 
     increaseGradesCapacity(); 
    } 
     grades[numGrades] = newGrade; 
     numGrades++; 
} 

public void increaseGradesCapacity() { 
    String[] newGrades = new String[grades.length + 1]; 
    for (int i = 0; i < grades.length; i++) { 
    newGrades[i] = grades[i]; 
    } 
    grades = newGrades; 
} 

目前,我有一個,而不必調用increaseGradesCapacity()方法測試一個測試案例:

@Test public void addGradeTest() { 
    String[] myGrades1 = {"a90", "a100", "q90", "q80", 
    "p100", "e87.5"}; 

    String[] myGrades2 = {"a90", "a100", "q90", "q80", 
    "p100", "e87.5", "q100"};    

    WeightedGrades2 wg = new WeightedGrades2("Aegon Targaryen", 6, myGrades1); 

    wg.addGrade("q100"); 

    Assert.assertArrayEquals("Test for addGrade.", 
    myGrades2, wg.getGrades());       
} 

但我試圖找出如何創建調用一個測試用例增加GradesCapacity()方法。這就是我現在所擁有的,但它仍然不能滿足Web-CAT的要求。有人有主意嗎?

@Test public void addGradeTest2() { 
    String[] myGrades1 = {"a90", "a100", "q90", "q80", 
    "p100", "e87.5"}; 

    String[] myGrades2 = {"a90", "a100", "q90", "q80", 
    "p100", "e87.5", null, "q100"}; 

    WeightedGrades2 wg = new WeightedGrades2("Anakin Skywalker", 7, myGrades1); 

    wg.increaseGradesCapacity(); 
    wg.addGrade("q100");    

    Assert.assertArrayEquals("Test for addGrade.", 
    myGrades2, wg.getGrades()); 
} 
+1

設計查詢:應該'increaseGradesCapacity'公開嗎?這看起來像內部API。但無論哪種方式,調用'addGrade'都會污染增加容量的測試......爲什麼不直接調用increaseGradesCapacity並測試該數組是否更大並且已正確保持內容? – Ash

回答

0

我不知道什麼是「網絡-CAT要求」必須在這種情況下滿意,但我會給你,希望回答您的問題一般的答案。

鑑於有問題的方法increaseGradesCapacity()負責增加數組的大小,我會簡單地在調用此方法之前和之後測試大小。所以,你的測試可能是這樣的:我

@Test public void addGradeTest2() { 
    String[] myGrades1 = {"a90", "a100", "q90", "q80", "p100", "e87.5"}; 
    WeightedGrades2 wg = new WeightedGrades2("Anakin Skywalker", 7, myGrades1); 

    int sizeBeforeIncrease = wg.getGrades().length; 

    wg.increaseGradesCapacity(); 

    int sizeAfterIncrease = wg.getGrades().length; 

    Assert.assertTrue("Expecting size after increase to be larger.", 
         sizeAfterIncrease > sizeBeforeIncrease); 
} 

注意如何拋棄了wg.addGrade('q100');線。如果您的第二個測試全權負責測試increaseGradesCapacity(),而addGrade方法會修改您最終想要檢查其大小的等級陣列,那麼它會使一個概念不準確,或者至少沒有被聚焦和包含。