我在freecodecamp上关注Java tutorial,并编写了以下代码。在这里,我创建了两个类:PersonTest.java和Person.java。我在PersonTest.java中编写了3个测试。在编写前两个测试时,已经创建了Person类的两个实例。在第三个测试中,它计算创建的实例数;我得到的输出为1(我希望它是2)。我不明白为什么会这样显示。任何帮助表示赞赏:)
PersonTest.java
package com.atharvajoshi.javacourse.lesson2;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class PersonTest {
@Test
public void shouldReturnHelloWorld() {
Person atharva = new Person(); // First instance
assertEquals("Hello World", atharva.helloworld());
}
@Test
public void shouldReturnHelloAtharva() {
Person person = new Person(); // Second instance
assertEquals("Hello Atharva", person.hello("Atharva"));
}
@Test
public void shouldReturnNumberOfPersons() {
System.out.println(Person.numberOfPersons()); // Answer is coming to be 1
assertEquals(2, Person.numberOfPersons()); // Test failed
}
}
Person.java
package com.atharvajoshi.javacourse.lesson2;
public class Person {
private static int personCounter = 0;
public Person() {
personCounter ++;
}
public String helloworld() {
return "Hello World";
}
public String hello(String anyName) {
return "Hello " + anyName;
}
public static int numberOfPersons() {
return personCounter;
}
}
输出:1