我正在尝试对我的课程进行单元测试,并模拟 DAO 以提供可预测的结果。尽管如此,当我收到休眠错误时,似乎仍在调用我的 DAO 方法。
org.hibernate.exception.GenericJDBCException:找不到站 TST。
这个错误是我的数据库不包含 TST 的结果,但是因为我模拟了 DAO,所以不应该调用它吗?我如何模拟调用,以便甚至不命中数据库。
这是我设置模拟的方式
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class MyServiceTest{
@Autowired
private MyService service;
private MyDAO dao;
private LinkedList objs;
@Before
public void init() throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
// mock the dao for predictable results
dao = mock(MyDAO.class);
when(dao.myDBCall(anyString(), any(Date.class))).thenReturn(legs);
Field f = MyService.class.getDeclaredField("dao");
f.setAccessible(true);
f.set(service, dao);
}
@Test
public void testCall() {
// construct our sample leg data
legs = new LinkedList();
//fill in my stub data i want to return
Collections.shuffle(legs);
List results = service.testingCall("TST", new Date()); // this fails because service is using the dao, but it is making a call to the DB with this garbage 'Test' param rather than just returning 'legs' as stated in my when clause
assertThat(results, not(nullValue()));
}
@Test
public void testGetGates() {
// fail("Not yet implemented");
}
@Test
public void testGetStations() {
// fail("Not yet implemented");
}
}