我的JUNIT测试显示了一个java空指针异常

时间:2014-01-30 13:26:29

标签: java junit

我的课程如下:

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

2 个答案:

答案 0 :(得分:3)

在尝试查找之前,您没有添加用户,因此结果对象为空。

编辑:

自从我回答后问题发生了变化,VD的回答是正确的 - 使用它。

答案 1 :(得分: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());

这应该有效