测试控制器方法时出现NullpointerException

时间:2012-11-29 07:22:04

标签: java testing junit jmock

这是一个我要用JUnit和JMock测试的控制器方法。

public String myMethod(ModelMap model, Principal principal,
                        @PathVariable MyObject obj) {
  if (obj != null) {
    Student student = getStudent(principal);
    if (check(obj, student)) {
      model.addAttribute(student).addAttribute(obj);
      return "page";
    }
  }
  return REDIR;
}


private boolean check(MyObject obj, Student student) {
  return student.getStudentNumber().longValue() == obj.getStudent().getStudentNumber().longValue();
}

我的测试

final StudentService studentService = context.mock(StudentService.class);

public void test() throws Exception {
  ModelMap model = new ModelMap();
  final MyObject = new myObject();

  context.checking(new Expectations() {
    {
      oneOf(studentService).getByNumber(SecurityHelper.getStudentNumberOf(Helper.getTestPrincipal()));
      will(returnValue(mockStudent));
    }
  });

  controller.myMethod(model, Helper.getTestPrincipal(), obj);
}

运行测试时,我得到一个指向check-method的NullPointerExeption。知道它来自哪里?是因为我缺乏一些期望吗? Student和obj不是可模拟的接口。我是新来的。哪种方法可以跟踪这类测试错误?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,这就是抛出异常的行:

return student.getStudentNumber().longValue() == obj.getStudent()
    .getStudentNumber().longValue();

所以异常可以来自几个地方:

  1. studenobj为空。
  2. student.getStudentNumber()返回null。
  3. obj.getStudent()返回null
  4. obj.getStudent().getStudentNumber()返回null。
  5. 对所有这些语句执行System.out并查看哪些语句为空。