使用 EasyMock 创建列表

Create a list with EasyMock

我目前正在学习 EasyMock 并且我已经阅读了一些关于它的教程。基于我获得的知识,我尝试创建一个模拟列表,但它给了我 AssertionError,我无法理解其原因。

基本上,我想要一个列表,第一个元素是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.

我在哪里犯了错误或者我除了模拟的错误 object/list?

看起来你是在告诉它期待:

get(0)
get(1)
size()

但实际的方法调用是:

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

使用 anyTimes() 方法禁用调用顺序和调用执行的检查。

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

您不希望在 for 循环中调用 .size(),请尝试:

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