我在主持人中有一个调用数据库的方法。现在,当我尝试测试实际与数据库通信的方法时,它会给我NullPointerException
。
我们如何实际处理此类情况?
public void getRoleFromSQLite(){
if ("tutor".equalsIgnoreCase(userDB.getValueFromSqlite("role",1)))
view.userRole("tutor");
else
view.userRole("student");
}
测试:
@Test
public void getRoleFromSqliteDatabaseTest(){
Mockito.doReturn("tutor").when(userDB).getValueFromSqlite("role",1)
presenter.getRoleFromSQLite();
Mockito.verify(viewMock).userRole("tutor");
}
例外:
java.lang.NullPointerException
at com.dolevel.level.db.UserDB.getValueFromSqlite(UserDB.java:130)
at com.dolevel.level.presenters.UserProfileScreenPresenter.getRoleFromSQLite(UserProfileScreenPresenter.java:28)
at com.dolevel.level.UserProfileScreenPresenterTest.getRoleFromSqliteDatabaseTest(UserProfileScreenPresenterTest.java:53)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
您只需要从:
中更改doReturn
句子 Mockito.doReturn("tutor").when(userDB).getValueFromSqlite("role",1)
to
Mockito.doReturn("tutor").when(userDB.getValueFromSqlite("role",1))
这样,您将嘲笑或录制 getValueFromSqlite
方法的调用,而不是在指定模拟行为时直接调用它。