0
我正在使用Mockito來模擬queryForObject,但我得到NPE。看起來我正在設置所需的一切。使用Mockito嘲笑queryForObject
long identity = getJdbcTemplate().queryForObject(getStatementConfiguration().getStatement(KeyConstants.CLIENT_USER_VENDOR_IDENTITY), Long.class);
是我得到NPE的地方。
MUT
public IClientUserVendorDto insert(final IClientUserVendorDto dto) throws DaoException {
try {
String sql1 = getStatementConfiguration().getStatement(KeyConstants.CLIENT_USER_VENDOR_RETRIEVE);
Object args[] = new Object[] {
dto.getClientUserId(),
dto.getVendor().getId(),
dto.getIdentifier(),
Boolean.TRUE,
dto.getCreatedBy(),
dto.getLastModifiedBy()};
//insert
String sql = getStatementConfiguration().getStatement(KeyConstants.CLIENT_USER_VENDOR_INSERT);
getJdbcTemplate().update(sql, args);
//Retrieve
long identity = getJdbcTemplate().queryForObject(getStatementConfiguration().getStatement(KeyConstants.CLIENT_USER_VENDOR_IDENTITY), Long.class);
return (ClientUserVendorDto) getJdbcTemplate().queryForObject(sql1, new Object[] {identity}, new ClientUserVendorRowMapper());
} catch (Exception e) {
String message = "An exception occurred inserting a Client User Vendor.";
IExceptionHandlerResponse r = getExceptionHandler().handleData(e, DaoException.class, message);
if (r.isRethrow()) {
DaoException daoe = (DaoException) r.getThrowable();
throw daoe;
}
throw (DaoException)r.getThrowable();
} finally {
}
}
Junit的
public void testInsert() throws Exception {
AppContext.setApplicationContext(applicationContext);
IVendorDto v = new VendorDto();
IClientUserVendorDto userDto = new ClientUserVendorDto();
userDto.setActive(true);
userDto.setClientUserId(new Long(1220));
userDto.setIdentifier("JUnit-ID");
userDto.setVendor(v);
v.setId(new Long(123));
userDto.setCreatedBy("SYSTEM");
userDto.setLastModifiedBy("Junit");
ClientUserVendorDao dao = new ClientUserVendorDao();
dao.setConfiguration(daoConfiguration);
dao.setJdbcTemplate(jdbcTemplate);
BaseJdbcDao baseDao = Mockito.mock(BaseJdbcDao.class);
BaseDao baseDao2 = Mockito.mock(BaseDao.class);
IStatementConfiguration stmtConfiguration = Mockito.mock(IStatementConfiguration.class);
Mockito.when(baseDao.getJdbcTemplate()).thenReturn(jdbcTemplate);
IDaoConfiguration configuration = new DaoConfiguration();
configuration.setStatement(stmtConfiguration);
dao.setConfiguration(configuration);
Mockito.when(baseDao.getJdbcTemplate().queryForObject(Mockito.any(String.class), (RowMapper<Long>) Mockito.any(Object.class))).thenReturn(123L);
userDto = dao.insert(userDto);
}
調試到該行然後檢查變量。找到一個爲null的對象,它可以是getJdbcTemplate()或getStatementConfiguration() –