模拟控制器类

时间:2017-02-28 16:27:23

标签: java unit-testing nullpointerexception jmockit

我想为下面代码中显示的方法编写一些测试。我正在使用JMockit模拟依赖项。无论出于何种原因,我一直得到一个NullPointerException,我真的不明白为什么会这样。我是JMockit的新手,一般都是嘲笑依赖。 Stack Trace只显示在行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));

    }
}

我认为我做的事情非常错误:(

2 个答案:

答案 0 :(得分:0)

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

@RunWith(JMockit.class)
public class ScheduleManagerTest {

...

答案 1 :(得分:0)

根据描述很难知道出了什么问题,但这是一个猜测:

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

subject.getTeacher().trim()

因为getTeacher()将返回null。要归还老师,您必须使用真实主题或使用

进一步嘲笑
Mockito.when(subject.getTeacher()).thenReturn(new Teacher());