我想模擬一個DAO方法在Spring/Hibernate中需要一個對象並返回一個對象。mockito方法傳遞對象時
Mockito.when(mockedDao.findByProperty(c)).thenReturn(state);
c
對象具有「名稱」,「本」等鍵值對。對象會有就業狀態。
但是當我運行測試時,它返回null。我認爲它是因爲我在單元測試中通過的參數criteria
並不完全相同,儘管它們是相同的。我該如何解決這個問題?這裏的標準是不相關的休眠條件鍵值的對象...
這裏是「service.getELementByName」:
@Override
@Transactional
public State getElementByName(Object value) {
Criteria c = new Criteria();
c.property = "state_name";
c.value = (String) value;
State result = (State) stateDAO.findByProperty(c);
return result;
}
請建議! 感謝
編輯 代碼看起來是這樣的
private State state;
@Mock
private StateDAO mockedDao;
@InjectMocks
private StateServiceImpl service;
@Before
public void init() {
// mockedDao = mock(StateDAO.class);
Criteria c = new Criteria();
c.property = "state_name";
c.value = (String) "Virginia";
state = new State();
state.setId(20);
state.setIntPtLat(37.5222512);
state.setIntPtLon(-78.6681938);
state.setStateName("Virginia");
Mockito.when(mockedDao.findByProperty(eq(c))).thenReturn(state);
// service = new StateServiceImpl<State>();
}
@Test
public void testFindByProperty() {
state = new State();
state.setId(20);
state.setIntPtLat(37.5222512);
state.setIntPtLon(-78.6681938);
state.setStateName("Virginia");
Criteria c = new Criteria();
c.property = "state_name";
c.value = (String) "Virginia";
Mockito.when(mockedDao.findByProperty(eq(c))).thenReturn(state);
service.getElementByName("Virginia");
State result = (State) service.getElementByName("Tes");
assertEquals(state, result);
}
需要更多代碼。什麼是「聯繫」對象?另外,如果可以的話,你應該檢查你以前的問題並接受一些答案。 – Paolo
更多的代碼肯定會有幫助! – Jonathan
其標準...我更新了代碼 –