2016-07-13 49 views
2

我目前正在學習EasyMock,我已經閱讀了一些關於它的教程。基於這些知識,我已經獲得了,我嘗試創建一個模擬列表,但它給了我AssertionError,其原因我無法理解。用EasyMock創建一個列表

基本上,我想有一個列表,它的第一個元素是1133L和第二個元素是1139L和它的大小是自然2.

我的方法

@Test 
public void testCreateIdealConf() 
{ 

List<Long> idList = createMock(List.class); 

expect(idList.get(0)).andReturn(1133L); 
expect(idList.get(1)).andReturn(1139L); 
expect(idList.size()).andReturn(2); 

replay(idList); 

for(int i = 0; i < idList.size(); i++) 
{ 
    System.out.println("Elements: " + idList.get(i)); 
} 
} 

當我運行這個測試方法,它提供了以下錯誤

java.lang.AssertionError: 
Unexpected method call List.size(): 
List.get(1): expected: 1, actual: 0 
List.size(): expected: 1, actual: 2 
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44) 
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94) 
at com.sun.proxy.$Proxy7.size(Unknown Source) 
at de.psi.passage3.auslieferung.allg.gui.status.CasBarUserConfigurationArrangementsTest.testCreateIdealConf(CasBarUserConfigurationArrangementsTest.java:113) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
at 
the rest of the failure trace is omitted. 

我在哪裏犯了一個錯誤還是我除了不對勁從模擬對象/列表?

+0

我沒有用了EasyMock,但它看起來像你告訴它期待'​​得到(0) get(1),size()',但實際的方法調用是:size(),get(0),size(),get(1),size()'。 – khelwood

+0

@khelwood現在,根據你的回答,我已經測試過,你是對的。該命令也很重要:)如果您更改您的評論作爲答案,它將被接受爲解決方案。 –

+0

很酷。很高興我能幫上忙。 – khelwood

回答

2

它看起來像你告訴它期望:

get(0) 
get(1) 
size() 

但實際的方法調用是:

size() 
get(0) 
size() 
get(1) 
size() 
1

使用anyTimes()方法來禁用調用順序和調用的檢查處決。

expect(idList.get(0)).andReturn(1133L).anyTimes(); 
expect(idList.get(1)).andReturn(1139L).anyTimes(); 
expect(idList.size()).andReturn(2).anyTimes(); 
+0

謝謝你的回答。我認爲,默認情況下,只要使用createMock而不是createStrictMock,就會禁用檢查呼叫順序和呼叫執行。 –

1

你是不是期待中的.size()呼籲循環,嘗試:

int listSize = 2 ; 
expect(idList.size()).andReturn(listSize).times(listSize+1); 
expect(idList.get(0)).andReturn(1133L); 
expect(idList.get(1)).andReturn(1139L);