如何在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