2017-10-18 59 views
1

爲了測試我的節目,我需要一個像嘲弄的方法調用:如何嘲笑嵌套方法的Java

entityManager.createQuery("SELECT...", Integer.class).getSingleResult() 

createQuery部分返回TypedQuery<Integer>,但我其實只是想返回一個整數: 1. 目前我正在使用Mockito爲了創建我的嘲笑,我對此很新。

有沒有一種測試方法?

謝謝!

+1

模擬結果,嘲笑結果。 –

+0

是的。而已。謝謝!我認爲那件事太複雜了。 –

回答

1

假設你有類EntityManager,Query。你可以像下面那樣嘲笑你的測試。 (模擬(),任(),()時......方法在的Mockito)

int result = 1; 
Query query = mock(Query.class); 
EntityManager entityManager = mock(EntityManager.class); 

when(entityManager.createQuery(any(), any()).thenReturn(query); 
when(query.getSingleResult()).thenReturn(result); 
+0

謝謝。爲我工作 –

0

嘲笑EntityManager,然後你可以預先定義的返回值。 Mockito.doReturn(1).when(entityManagerMock).createQuery(any(String.class), any());