Reputation: 1178
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...
Upvotes: 0
Views: 4315
Reputation: 308743
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
}
Upvotes: 3
Reputation: 4692
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
}
Upvotes: 0
Reputation: 471
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:
Upvotes: 0