java test objects with static field

4.1k Views Asked by At

I have the object with static field:

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

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

Now I want to test this class with multiple tests. The problen is that my objects are not deleted from memory when one test is completed:

@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
}

Is there any way I can flush them after each test? Since the only way I can overcome it - using Ignoring...

3

There are 3 best solutions below

0
On BEST ANSWER

I don't think this is well written.

If I interpret this correctly, you want a unique projectid associated with each instance that is calculated from the static count. Change your code like this:

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
}

This way projectid will start with zero and increment by one each time you create a new instance.

You shouldn't be worrying about flushing or what the project id count is. That's not material for your method tests.

If you must reset to zero, make the static variable 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
}

Here's how you reset it in your tests (if you must):

@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
}
0
On

Static objects are created when application starts and it has only one instance. It is referred as Class variable. Refer this SO question.

So whenever you are doing id++; it is actually updating that single class level id object. And this.id really does not make sense.


@duffymo correctly pointed out. You need this in your constructor.

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

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

First of all, this is the main reason that static variables of that kind are frowned upon.

If you really have to, you have a couple of options:

  1. Use the class loader to unload and then reload the class between tests
  2. Using introspection to reset the value between tests, maybe initialise the static to a constant, then you can use the same constant to reset it