简体   繁体   中英

Static variable bug in Java

I have written a simple class and 3 tests as follows:

Person.java:

package MyPackage;

public class Person {
    
    private static int PERSON_COUNTER = 0;
    
    public Person() {
        PERSON_COUNTER++;
    }
    
    public String hello(){
        return "Hello World";
    }
    
    public String helloName(String name) {
        return "Hello "+name;
    }
    
    public static int numberOfPersons() {
        return PERSON_COUNTER;
    }
    
}

PersonTest.java:


package Test;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import MyPackage.Person;

public class PersonTest {
    
    @Test
    public void testHello() {
        Person p = new Person();
        assertEquals("Hello World",p.hello());
    }
    
    @Test
    public void testHelloName() {
        Person p1 = new Person();
        assertEquals("Hello Mile",p1.helloName("Mile"));
    }
    
    @Test
    public void numberOfPersons() {
        Person p2 = new Person();
        Person p3 = new Person();
        Person p4 = new Person();
        assertEquals(3, Person.numberOfPersons());
    }
}

The test numberOfPersons fails with message: java.lang.AssertionError: expected:<3> but was:<4> The fourth object person is being counted from testHello test and I don't seem to find reason why is that happening.

You should use a method with the annotation @BeforeEach, that cleans your environment by resetting the variables, I think this is what you are missing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM