我试图在 Spring/Hibernate 中模拟一个 DAO 方法,它接受一个对象并返回一个对象。
Mockito.when(mockedDao.findByProperty(c)).thenReturn(state);
c
对象具有键值对,例如“name”、“ben”。state
对象将具有就业状态。
但是当我运行测试时它返回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);
}