如何在JAVA中測試toString?我想這和普通測試是一樣的概念,但我真的有很多問題。在我的Big JAVA教科書中找不到這些信息。我已閱讀了至少5次所有章節。我只是沒有看到它,而這在任何作業中都沒有涉及。JAVA中的單元測試toStrings
對於其中一個,我不明白在第一個例子中代碼的單元測試中,我的老師在assertTrue(text.contains(num))中放入了「num」;
我覺得她把num放進去,因爲我們遵循WholeLife策略的格式。防爆。
WholeLifePolicy policy = new WholeLifePolicy(num, value, years, name);
我以爲這是一個例子,我會做同樣的事情,例如面值如下所示。
assertTrue(text.contains("Face Value:"));
assertTrue(text.contains(value));
這不會編譯,因爲它表示它不兼容,因爲數字是雙精度型。所以我嘗試了兩次。唯一編譯的是「num」
所以很明顯,我的測試都沒有通過。這是我的代碼。對於WholeLifePolicy類,請遵循測試類。
爲什麼使用「num」?它是否因爲它是策略對象的顯式參數?或者是僅僅因爲一個數字是在那裏」或其他原因
顯然我所有的代碼是低於//評論其他的一切在實驗室源還
/**
* Return a string representation of the WholeLifePolicy.
*
* @return String output string.
*
* <pre>
* Produce output in the following format:
*
* Policy Information:
* Policy #: WLP1000000
* Policy Years: 20
* Face Value: 50000.0
* Beneficiary: John Doe
*
* </pre>
*/
public String toString()
{
String output = "Policy Information:\n";
output = output + "Policy #: " + this.getPolicyNum() + "\n";
// your code here, finish the output string
output = output + "Face Value" + this.getFaceValue() + "\n";
output = output + "Policy Years:" + this.getPolicyYrs() + "\n";
output = output + "Beneficiary" + this.getBeneficiary() + "\n";
return output;
}
}
測試類:。
/**
* Test the toString method.
*/
@Test
public void testToString()
{
String num = "WLP1234567";
double value = 50000.0;
int years = 20;
String name = "Katie Perry";
WholeLifePolicy policy = new WholeLifePolicy(num, value, years, name);
String text = policy.toString();
assertTrue(text.contains("Policy Information:"));
assertTrue(text.contains("Policy #:"));
assertTrue(text.contains(num));
// your code here, finish the testing of the toString() method
// checking for both the headings and face value, policy years
assertTrue(text.contains("Face Value:"));
assertTrue(text.contains(num));
assertTrue(text.contains("Policy Years:"));
assertTrue(text.contains(num));
assertTrue(text.contains("Beneficiary:"));
assertTrue(text.contains(num));
}
}
這是一個很好的問題。這是因爲這本Big Java書籍非常簡短地介紹了2頁的單元測試,而且我完全搞不清楚這些測試是如何測試事情的,以及它們如何甚至是連接到普通課程。我真的需要爲初學者編寫的初學者信息,它將單元測試分解成不同的部分,並解釋每個部分的作用和原因。我在許多,許多小時之後仍然在爲這個toString類而努力。 – jforrest1980