![](/img/trans.png)
[英]Nullpointerexception EasyMock when testing Controller
[英]NullpointerException when testing a controller method
這是我將要使用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);
}
運行測試時,我得到一個NullPointerExeption
,它指向檢查方法。 知道那是哪里來的嗎? 是因為我缺乏期望嗎? Student和obj不是可模擬的接口。 我是新來的。 跟蹤此類測試錯誤的最佳方法是哪種?
如果我正確理解您的意見,這是引發異常的行:
return student.getStudentNumber().longValue() == obj.getStudent()
.getStudentNumber().longValue();
因此,異常可能來自幾個地方:
studen
或obj
為null。 student.getStudentNumber()
返回null。 obj.getStudent()
返回null obj.getStudent().getStudentNumber()
返回null。 在所有這些語句上執行System.out,看看哪個為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.