0

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", "[email protected]", "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("[email protected]", 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);
 }

1 Answer 1

1

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

UserService svc = new UserService(context)

Sign up to request clarification or add additional context in comments.

1 Comment

I changed it to use the UserService interface (IUserService) and created it as you said and it passed, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.