JUnit Testing Android NullPointerException Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of JUnit Testing Android NullPointerException without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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;

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

    //assert - that testUser is not null

    //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){
    dbContext = new DbContext(context);

public User SaveUserProfile(User u) {
    User user = new User();


    return user;


public interface IUserService {

User SaveUserProfile(User u);


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

UserService svc = new UserService(context)

We are here to answer your question about JUnit Testing Android NullPointerException - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji