我想单元测试我的类,并模拟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");
}
}
不幸的是H2不是一个选项。至于“自己做”,我的服务还有许多其他的bean需要自动注入,这使得这种方法不切合实际。真的没有办法完全嘲弄道? – 75inchpianist 2013-03-13 22:46:29
你可以。首先,将你的hibernate相关的xml配置移到一些(“dev”)Spring配置文件(谷歌的“spring配置文件”)。然后创建dao的存根(模拟)实现并将其放到“测试”配置文件中。在测试中添加@ActiveProfiles(“test”)注释之后(您还需要在常规应用程序启动时激活“dev”配置文件)。如果你不喜欢配置文件 - 在3个文件(applicationContext.xml,dev.xml,mock.xml)中拆分配置 – 2013-03-13 22:56:25
并且还检查 - https://bitbucket.org/kubek2k/springockito/wiki/Home – 2013-03-13 22:59:01