2014-11-05 157 views
-1

如何測試一個類中的默認構造函數,然後在不同的類中測試它? 這是具有默認構造函數的Person類的代碼。 我不確定在PersonTester類中如何訪問這個默認的構造函數以及如何測試它 - 到目前爲止第二課的內容也在下面。如何測試Java中不同類的默認構造函數

任何幫助將長久地感謝,謝謝:)

class Person { 

    // Data Members 
    private String name; // The name of this person 
    private int age; // The age of this person 
    private char gender; // The gender of this person 

    // Default constructor 
    public Person() { 
     name = "Not Given"; 
     age = 0; 
     gender = 'U'; 
    } 

    // Constructs a new Person with passed name, age, and gender parameters. 
    public Person(String personName, int personAge, char personGender) { 
     name = personName; 
     age = personAge; 
     gender = personGender; 
    } 

    // Returns the age of this person. 
    public int getAge() { 
     return age; 
    } 

    // Returns the gender of this person. 
    public char getGender() { 
     return gender; 
    } 

    // Returns the name of this person. 
    public String getName() { 
     return name; 
    } 

    // Sets the age of this person. 
    public void setAge(int personAge) { 
     age = personAge; 
    } 

    // Sets the gender of this person. 
    public void setGender(char personGender) { 
     gender = personGender; 
    } 

    // Sets the name of this person. 
    public void setName(String personName) { 
     name = personName; 
    } 

} // end class  

import java.util.Scanner; 

public class PersonTester { 

    // Main method 
    public static void main(String[] args){ 

     // TEST THE DEFAULT CONSTRUCTOR FIRSTLY. 

     // Create an instance of the Person class. 
     Person person1 = new Person(); 

     Scanner input = new Scanner(System.in); 

     // Get the values from user for first instance of Person class. 
     System.out.println("Person 1 Name: "); 
     person1.setName(input.nextLine()); 

     System.out.println("Person 1 Age: "); 
     person1.setAge(input.nextInt()); 

     System.out.println("Person 1 Gender: "); 
     person1.setGender(input.next().charAt(0);); 

     // Alternatively assign values to the Person class. 
     // person1.setName("Not Given"); 
     // person1.setAge(0); 
     // person1.setGender("U"); 
    } 
} 
+0

問題是什麼?你在你的第二個片段中調用默認的構造函數,所以沒關係 – Dici 2014-11-05 15:01:47

回答

1

您的測試看起來像:

@Test 
public void testDefaultConsturctor(){ 
    Person person = new Person(); 
    Assert.assertEquals(person.getName(),"Not Given"); 
    Assert.assertEquals(person.getAge(),0); 
    Assert.assertEquals(person.getGender(),'U'); 
} 
0

您可以在第二類測試默認的構造函數,而不使用與該代碼

斷言
Person defaultPerson = new Person(); 
System.out.print("My default name is: " + defaultPerson.getName()); 
System.out.print("My default age is: " + defaultPerson.getAge()); 
System.out.print("My default gender is: " + defaultPerson.getGender()); 

順便說一句,我不知道是什麼問題,因爲你打電話給德(PersonTester)