0

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.

5
  • 6
    Do you realise that testHello and testHelloName also create Persons? Commented Jan 29, 2022 at 15:28
  • Yes I do but why it isn't 5 then, why only testHello increases static variable? Commented Jan 29, 2022 at 15:33
  • 4
    Do you realise that JUnit could run your tests in any order? Commented Jan 29, 2022 at 15:33
  • No I did not, thank you, I need to run the tests separately. Commented Jan 29, 2022 at 15:38
  • 1
    This kind of effect is exactly why static state is nearly always a bad idea. Commented Jan 29, 2022 at 16:55

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.