图 1. JUnit 编译失败
显然,我还没有 Person
类,所以运行该测试会出现问题 — JUnit 给出了一个红条。如果可以运行,并通过测试,则会显示一个绿条。您的目标总是设法得到一个绿条。别忘了,JUnit 的座佑铭是“得到绿条,使代码干净”(有时抱怨是难免的)。
没问题。我将创建 Person
类,如清单 2 所示:
package com.roywmiller.testexample; public class Person { public int getAge() { return 0; } } |
现在,当运行这个测试时,测试通过,应该可以看到一个绿条。我必须从 getAge()
返回值,否则不会编译它。这里碰巧 0 最方便,0 被认为是新的 Person
实例的缺省值,所以工作正常。再次重申,我只编写了通过测试所需的代码。
能够使 Person
具有缺省的年龄值固然很好,但这对我的系统不会有太大帮助。 Person
需要比这更智能些。我真正所需要的是, Person
拥有其生日,并能回答其当前的年龄。这意味着 Person
对象的年龄会随时间的推移而增长。在进行编码前,将 testGetAge
重命名为 testGetDefaultAge
(清楚地表明,我正在测试缺省的年龄),并为这个测试案例编写另一个测试方法,如清单 3 所示:
public void testGetAge() { GregorianCalendar calendar = new GregorianCalendar(1971, 3, 23); person.setBirthDate(calendar.getTime()); int actual = person.getAge(); assertEquals(31, actual); } |
还不能编译这个测试(您注意到了其中的模式吗?),因为 Person
内没有 setBirthDate()
方法。在创建了这个方法之后, Person
将类似于清单 4 所示:
package com.roywmiller.testexample; import java.util.Date; public class Person { protected Date birthdate; public int getAge() { return 0; } public void setBirthDate(Date aBirthDate) { this.birthdate = aBirthDate; } } |
Person
中的 getAge()
仍然没有什么变化,所以测试失败。图 2 显示了 JUnit Fast View 中出现的信息: