通常我會發現自己爲getter \ setter,c'tors和Object方法(hashCode,equals和toString)創建了相同的單元測試方法。 我想在Eclipse IDE的幫助下實現這個過程的自動化。 考慮這個例子:使用eclipse模板創建測試用例
public Class Person {
private String id;
private String name;
public Person(String id, String name){
this.id = id;
this.name = name;
}
public String getId() { return id; }
public void setId(String id) {
this.id = id;
}
public String getName() { return name; }
public void setName(String name) {
this.name = name;
}
@override
public int hashCode(){ ... }
public boolean equals(Person other){ ... }
public String toString(){ ... }
/* this class may implement other logic which is irrelevant for the sake of question */
}
單元測試類會是這個樣子:
public class PersonTest extends TestCase
{
@override
public void setup() {
Person p1 = new Person("1","Dave");
Person p2 = new Person("2","David");
}
@override
public void tearDown() {
Person p1 = null;
Person p2 = null;
}
public void testGetId() {
p1.setId("11");
assertEquals("Incorrect ID: ", "11", p1.getId());
}
public void testGetName() { /* same as above */ }
public void testEquals_NotEquals() { /* verify that differently initialized instances are not equals */ }
public void testEquals_Equals() { /* verify that an object is equals to itself*/ }
public void testHashCode_Valid() { /* verify that an object has the same hashcode as a similar object*/ }
public void testHashCode_NotValid() { /* verify that different objects has different hashcodes*/ }
public void testToString() { /* verify that all properties exist in the output*/ }
}
這骨架相似,絕大多數創建的類。 它可以自動化與Eclipse?
謝謝Nilesh,我會看看 – 2011-03-17 12:32:59
這個插件非常適合創建單元測試。 – javaguy 2011-03-19 20:45:43