java 具有静态场的测试对象

java test objects with static field

我有带静态字段的对象:

class Project() {
  private static id;
  private int projectid;

  public Project(fileds) {
    this.id = id++;
  }
  //methods
  }

现在我想用多个测试来测试这个class。问题是当一个测试完成后,我的对象没有从内存中删除:

@Test
public test1(){
  Project project1 = new Project();
  Project project2 = new Project();
}
@Test
public test2(){
  here the objects from previous tests are still exist since the   static    field is two times increased
}

有什么方法可以在每次测试后冲洗它们吗?因为我可以克服它的唯一方法 - 使用忽略...

静态对象是在应用程序启动时创建的,它只有一个实例。它被称为 Class variable。参考这个 SO question.

因此,无论何时执行 id++;,它实际上都在更新单个 class 级别 ID 对象。而且this.id真的没有意义。


@duffymo 正确指出。你的构造函数中需要这个。

class Project { // removed "()" 
  private static int id; // added int
  private int projectid;

  public Project() { // removed fileds
    this.projectid = Project.id++; // updated
  }
  //methods
}

我觉得这篇写的不太好

如果我对此的解释正确,您需要一个唯一的 projectid 与根据静态计数计算的每个实例相关联。像这样更改您的代码:

class Project() {
  private static int id;
  private int projectid;

  public Project(fileds) {
    // This notation makes clear that the static variable associated w/ class
    this.projectid = Project.id++;
  }
  //methods
}

这样 projectid 将从零开始,每次创建新实例时递增 1。

您不必担心刷新或项目 ID 计数是多少。对于您的方法测试,这不是 material。

如果一定要归零,使静态变量public:

class Project() {
  public static int id;
  private int projectid;

  public Project(fileds) {
    // This notation makes clear that the static variable associated w/ class
    this.projectid = Project.id++;
  }
  //methods
}

以下是您在测试中重置它的方法(如果必须):

@Test
public test1(){
  Project.id = 0;
  Project project1 = new Project();
  Project project2 = new Project();
}
@Test
public test2(){
  // reset the count
  Project.id = 0;
  // here the objects from previous tests are still exist since the   static    field is two times increased
}

首先,这是那种静态变量不受欢迎的主要原因。

如果你真的需要,你有几个选择:

  1. 使用 class 加载器卸载然后在测试之间重新加载 class
  2. 使用内省来重置测试之间的值,也许将静态初始化为常量,然后您可以使用相同的常量来重置它