模拟控制器时出现 NullPointerException class

NullPointerException when mocking controller class

我想为下面代码中显示的方法编写一些测试。我正在模拟 JMockit 的依赖关系。无论出于何种原因,我一直收到 NullPointerException,我真的不明白为什么会这样。我是 JMockit 的新手,一般来说是模拟依赖项。堆栈跟踪仅显示在第 new NonStrictExpectations() 行抛出的 NullPointerException .

测试方法:

@Override
public boolean addSubject(User user, Schedule schedule, SchoolSubject subject) {
    final boolean result = schedule.addSubject(subject.getHourTime(), subject);
    scheduleDAO.update(schedule);
    if (subject.getTeacher() != null && !subject.getTeacher().trim().isEmpty()) {
        for (final TeacherEntry teacher : user.getTeachers()) {
            if (subject.getTeacher().equals(teacher.getName())) {
                teacher.getSubjects().add(subject.getName());
                teacherDAO.update(teacher);
            }
        }
    }
    try {
        userDAO.update(user);
    } catch (final DuplicateUniqueFieldException e) {
        throw new UnexpectedUniqueViolationException(e);
    }
}

测试方法:

//imports not copied
public class ScheduleManagerTest {

@Tested
ScheduleManager manager;

@Injectable
UserDAO userDAO;

@Injectable
ScheduleDAO scheduleDAO;

@Injectable
TeacherEntryDAO teacherDAO;

@Injectable
SchoolSubjectDAO schoolSubjectDAO;

@Mocked
Schedule schedule;

@Mocked
SchoolSubject subject;

@Mocked
User user;

@Test
public void testAddSubject() throws DuplicateUsernameException, DuplicateEmailException {

    new NonStrictExpectations() {

        {
            schedule.addSubject(anyInt, (SchoolSubject) any);
            result = true;
            scheduleDAO.update((Schedule) any);
            subject.getTeacher();
            result = anyString;
            subject.getTeacher().trim().isEmpty();
            result = false;
            user.getTeachers();
            result = (ArrayList<TeacherEntry>) any;
            teacherDAO.update(((TeacherEntry) any));
            userDAO.update((User) any);
        };
    };

    assertTrue(manager.addSubject(user, schedule, subject));

    }
}

我觉得我做错了:(

您需要将 @RunWith(JMockit.class) 添加到您的 class

@RunWith(JMockit.class)
public class ScheduleManagerTest {

...

根据描述很难知道问题出在哪里,但这里有一个猜测:

默认情况下,模拟对象的方法中 return 为 null。你会在这里得到一个空指针:

subject.getTeacher().trim()

因为 getTeacher() 将 return 为空。对于 return 老师,您必须使用真实主题或使用

进行进一步模拟
Mockito.when(subject.getTeacher()).thenReturn(new Teacher());