简体   繁体   English

JUnit 测试 Android NullPointerException

[英]JUnit Testing Android NullPointerException

My project is using a Firebase Realtime Database as its DB storage.我的项目使用 Firebase 实时数据库作为其数据库存储。 I am using MVC architecture with a repository and service layer.我正在使用带有存储库和服务层的 MVC 架构。 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.我在下面的行中收到 null 指针异常,我不知道为什么。 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.您的svc是 object 未创建。 Create it before using:在使用之前创建它:

UserService svc = new UserService(context)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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