2014-01-30 98 views
-1

我班如下:我的JUnit測試是顯示一個Java空指針異常

package Productions; 

import java.util.Vector; 

public class SetOfUsers extends Vector<User> { 
    private static SetOfUsers register = null; 

    public SetOfUsers(){ 
     super(); 
    } 

    public static SetOfUsers getInstance(){ 
     if (register == null) { 
      register = new SetOfUsers(); 
     } 
     return register;  
    } 

    public void addUser(User aUser){ 
     super.add(aUser); 
    } 

    public User findUserByName(String name){ 
     for(int i = 0; i < size(); i++){ 
      User user = elementAt(i); 
      if(user.getName().equals(name)){ 
       return user; 
      } 
     } 
     return null; 
    } 
} 

這裏是我的用戶類

package Productions; 

public class User { 
    private final String name; 
    private final String password; 
    private String projectName; 
    private String type; 


    public User(String name, String password,String type){ 
    this.name = name; 
    this.password = password; 
    this.type = type; //type of user 

    } 



    public boolean checkPassword(String pass) 
    { 
     if(password.equals(pass)) 
      return true; 
      else 
      return false; 

    } 
    public String getName(){ 
     return name; 
    } 
    public String getPassword(){ 
     return password; 
    } 
    public String getType(){ 
     return type; 
    } 
    public void allocateTask(){ 

    } 
    public void removeTask(){ 

    } 


    @Override 
    public String toString() { 
     return "Staff Name: " + this.getName() + 
       ", Staff Pass: " + this.getPassword(); 
    } 

} 

以上就是我測試的類,它擁有一個setOfUser名稱

public void testFindUserByName() { 
    String name = "Bob"; 
    SetOfUsers instance = new SetOfUsers(); 
    // User expResult = null; 
    //User result = instance.findUserByName(name); 
    //assertEquals(expResult, result); 
    User result; 
    instance.add(result); 
    // User result = instance.findUserByName(name); 

    //then 
    assertEquals("Bob", result.getName()); 
} 

當我運行上述測試時,我得到一個java空指針異常,我不明白這應該是因爲我期待Bob這個名字。

+0

試圖瞭解究竟是什麼類是指設計! –

回答

3

您在嘗試查找它之前未添加用戶,因此結果對象爲空。

編輯:

自從我回答改變的問題,VD的答案下面是正確的 - 使用。

+0

我該如何添加用戶?和哪裏? – user3253321

+0

@ user3253321看起來像你不明白你在做什麼,可能是你應該在嘗試添加測試之前學習你的'SetOfUser' – 2014-01-30 13:35:32

1
//following will create a user 
User user = new User("UserName1","password","type"); 

//following will add a user in setOf users 
SetOfUsers instance = new SetOfUsers(); 
instance.add(user); 

//so now you have a set of users having a user with name as "UserName1" now do following 

User result = instance.findUserByName("UserName1"); 
assertEquals("UserName1", result.getName()); 

這應該工作

+0

我的用戶類沒有setName方法 – user3253321

+0

編輯了ans,請通過Java的基礎知識第一。 –