0

Here is a controller method I'm about to test with JUnit and 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();
}

My test

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);
}

When running test, I get a NullPointerExeption which points to check-method. Any idea where that comes from? Is it because I lack some expectation? Student and obj are not interfaces to be mockable. I'm new with this. Which is the best way to track these kind of testing errors?

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
mjgirl
  • 1,214
  • 7
  • 24
  • 42
  • 4
    Please post your stacktrace. Also, please show the code in your test where you mock the `studentService`. – Duncan Jones Nov 29 '12 at 08:24
  • I added the mocking. Tracktrace points to line number on controller method where is the if clause and on test where I call controller.test-method – mjgirl Nov 29 '12 at 09:01
  • One way to pinpoint null pointer is to split statement up to use temp variables. That is, when you have `method1(methdo2()).method3()...`, change that to `temp2 = method2(); temp1 = method1(temp2); temp1.method3()...`. – hyde Nov 29 '12 at 09:08
  • None of the parametres given to check method is null. – mjgirl Nov 29 '12 at 09:28

1 Answers1

1

If i understand you correctly, this is the line that throws an exception:

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

So the exception can come from several places:

  1. studen or obj are null.
  2. student.getStudentNumber() returns null.
  3. obj.getStudent() returns null
  4. obj.getStudent().getStudentNumber() returns null.

Do a System.out on all of these statements and see which is null.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
Tomer
  • 17,787
  • 15
  • 78
  • 137