我想單元測試我的類,並模擬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