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); }
Answer
Your svc
is object not created. Create it before using:
UserService svc = new UserService(context)