如何使用EasyMock模拟DynamoDB的ItemCollection <QueryResult>?

Max*_*Max 5 java easymock amazon-web-services amazon-dynamodb

我有以下Java代码:

Index userNameIndex = userTable.getIndex("userNameIndex");
ItemCollection<QueryOutcome> userItems = userNameIndex.query("userName", userName);

for (Item userItem : userItems) {
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试编写一个单元测试,我想嘲笑ItemCollection<QueryOutcome>.问题是返回的迭代器ItemCollection<QueryOutcome>::iterator是类型IteratorSupport,它是一个包受保护的类.因此,无法模拟此迭代器的返回类型.我该怎么做?

谢谢!

小智 1

这可能不是最好的方法,但它有效,并且可能需要您更改在被测试的类中获取迭代器的方式。

@Test
public void doStuff() throws ClassNotFoundException {

    Index mockIndex;
    ItemCollection<String> mockItemCollection;
    Item mockItem = new Item().with("attributeName", "Hello World");

    mockItemCollection = EasyMock.createMock(ItemCollection.class);

    Class<?> itemSupportClasss = Class.forName("com.amazonaws.services.dynamodbv2.document.internal.IteratorSupport");
    Iterator<Item> mockIterator = (Iterator<Item>) EasyMock.createMock(itemSupportClasss);

    EasyMock.expect(((Iterable)mockItemCollection).iterator()).andReturn(mockIterator);     
    EasyMock.expect(mockIterator.hasNext()).andReturn(true);
    EasyMock.expect(mockIterator.next()).andReturn(mockItem);
    EasyMock.replay(mockItemCollection, mockIterator);

    /* Need to cast item collection into an Iterable<T> in 
       class under test, prior to calling iterator. */
    Iterator<Item> Y = ((Iterable)mockItemCollection).iterator();
    Assert.assertSame(mockItem, Y.next());

}
Run Code Online (Sandbox Code Playgroud)