这是一个我要用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不是可模拟的接口。我是新来的。哪种方法可以跟踪这类测试错误?
答案 0 :(得分:1)
如果我理解正确,这就是抛出异常的行:
return student.getStudentNumber().longValue() == obj.getStudent()
.getStudentNumber().longValue();
所以异常可以来自几个地方:
studen
或obj
为空。student.getStudentNumber()
返回null。obj.getStudent()
返回null obj.getStudent().getStudentNumber()
返回null。对所有这些语句执行System.out并查看哪些语句为空。