How to make fun of DynamoDB ItemCollection <QueryResult> using EasyMock?
I have the following Java code:
Index userNameIndex = userTable.getIndex("userNameIndex");
ItemCollection<QueryOutcome> userItems = userNameIndex.query("userName", userName);
for (Item userItem : userItems) {
}
I am trying to write unit test and I would like to make fun ItemCollection<QueryOutcome>. The problem is that the iterator returned ItemCollection<QueryOutcome>::iteratoris of type IteratorSupportwhich is the class protected by the package. Therefore, it is impossible to mock the return type of this iterator. What can I do instead?
Thank!
+4
2 answers
This may not be the best way to do this, but it works and may require you to change the way you get the iterator in the test class.
@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());
}
+1
. , Iterable ItemCollection, .
Iterable<Item> mockItemCollection = createMock(Iterable.class);
Iterator<Item> mockIterator = createMock(Iterator.class);
Item mockItem = new Item().with("attributeName", "Hello World");
expect(mockItemCollection.iterator()).andReturn(mockIterator);
expect(mockIterator.hasNext()).andReturn(true).andReturn(false);
expect(mockIterator.next()).andReturn(mockItem);
replay(mockItemCollection, mockIterator);
for(Item i : mockItemCollection) {
assertSame(i, mockItem);
}
verify(mockItemCollection, mockIterator);
, , , . .
AWS, , . . , -, .
ItemCollection :
public class ItemCollectionWrapper<R> implements Iterable<Item> {
private ItemCollection<R> wrapped;
public ItemCollectionWrapper(ItemCollection<R> wrapped) {
this.wrapped = wrapped;
}
public Iterator<Item> iterator() {
return wrapped.iterator();
}
}
+1