我正在尝试对班级进行单元测试,并模拟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");
}
}
最佳答案
首先,检查PowerMock而不是Field f = MyService.class.getDeclaredField("dao");
(检查Whitebox
)
模拟一个对象不会阻止休眠模式启动(因为您正在加载applicationContext.xml
,因此休眠模式将尝试连接到DB)。您的模拟-它只是一个测试实例的一个字段上的POJO,而不是Spring bean或类的替代品。
如果您只想测试dao和service类(创建清晰的单元测试),请从测试中删除与Spring相关的批注,然后自己进行(创建模拟,创建服务,将模拟放入服务并进行测试)。
如果要使用Spring上下文测试应用程序(创建集成测试),请为休眠创建H2 in-memory database并仅测试服务(不要忘记在@After
中清除它)。
第三种方法-将您的配置文件分成两个Spring配置文件(例如dev
和test
)并自己实现模拟(将模拟转换为test
,将真正的休眠模式和dao转换为dev
)。
如果您不想使用Spring概要文件,则可以将applicationContext.xml
分为3个文件(对于普通bean,对于实际DB bean,对于模拟)。
还有一种更性感的方式-使用springockito-annotations(但您仍然需要避免加载休眠状态)