简体   繁体   中英

JUnit Testing Android NullPointerException

My project is using a Firebase Realtime Database as its DB storage. I am using MVC architecture with a repository and service layer. I'm trying to unit test a method in the service layer that adds a new user to the database repository.

I'm getting a null pointer exception on the line below and I don't know why. Any ideas?

User testUser = svc.SaveUserProfile(u);

Here is my unit test code:

public class RegistrationActivityTest {

UserService svc;

@Test
public void testAddUserToDb_WhenNone_ShouldSetAllProperties(){
    //act
    User u = new User("1", "John", "john@email.com", "Teacher");
    User testUser = svc.SaveUserProfile(u);

    //assert - that testUser is not null
    assertNotNull(testUser);

    //now assert that the user properties were set correctly
    assertEquals("1", testUser.getUserId());
    assertEquals("John", testUser.getName());
    assertEquals("john@email.com", testUser.getEmail());
    assertEquals("Teacher", testUser.getAccount());
}

Here is my service layer and interface code:

public class UserService implements IUserService {

//instance of DbContext for firebase handling
private DbContext dbContext;

public UserService(Context context){
    super();
    dbContext = new DbContext(context);
}

@Override
public User SaveUserProfile(User u) {
    User user = new User();
    user.setUserId(u.getUserId());
    user.setName(u.getName());
    user.setEmail(u.getEmail());
    user.setAccount(u.getAccount());

    dbContext.AddUserAccount(user);

    return user;
}

Interface:

public interface IUserService {

User SaveUserProfile(User u);
 }

Your svc is object not created. Create it before using:

UserService svc = new UserService(context)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM