使用eclipse模板创建测试用例

Ass*_*ato 5 java eclipse junit

我经常发现自己为getter\setters,c'tors和Object方法(hashCode,equals和toString)创建了相同的单元测试方法.在Eclipse IDE的帮助下,我想要实现的是这个过程的自动化.考虑这个例子:

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 */
}
Run Code Online (Sandbox Code Playgroud)

单元测试类看起来像这样:

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*/ }
}
Run Code Online (Sandbox Code Playgroud)

这个骨架类似于创建的绝大多数类.可以用Eclipse自动化吗?

Nil*_*esh 11

看看快速代码.它是一个eclipse插件,提供了非常好的模板化功能,这是你似乎正在寻找的东西.在文档页面上查找"创建单元测试"部分.

此插件的一个非常有用的功能是自动创建单元测试.单元测试可以是Junit 3,Junit 4或TestNG.对于Junit 4或TestNG测试,将自动添加适当的注释.一个人只需要配置一次.

  • 谢谢Nilesh,我来看看 (2认同)
  • 这个插件非常适合创建单元测试. (2认同)