努力模拟在Java/Mongo中使用汇总时要返回的内容。
我曾尝试使用Mongocursor,但努力理解这一点。我想对此进行单位测试涵盖所有路径。使用Mockito和Testng的最佳方法是什么。
public List<User> getAggregatedList(User user){
AggregateIterable<User> agg = collection.aggregate(pipeline, User.class)
List<User> users = new ArrayList<>();
if (agg != null){
Iterator<User> it = agg.iterator();
while(it.hasNext()){
users.add(it.next());
}
}
return users;
}
我应该能够编写一个测试,例如:
...
expected = Arrays.asList(user1,user2...)
verify(result,expect)
您可以通过模拟迭代器的hasnext((和next((方法来测试它:
@Test
public void testGetAggregatedList() {
MongoCollection collection = PowerMockito.mock(MongoCollection.class);
AggregateIterable<User> iterable = PowerMockito.mock(AggregateIterable.class);
MongoClient client = PowerMockito.mock(MongoClient.class);
MongoDatabase db = PowerMockito.mock(MongoDatabase.class);
MongoCursor iterator = PowerMockito.mock(MongoCursor.class);
User user1 = PowerMockito.mock(User.class);
User user2 = PowerMockito.mock(User.class);
MongoDaoDelegator.setClient(client);
PowerMockito.when(client.getDatabase(anyString())).thenReturn(db);
PowerMockito.when(db.getCollection(anyString())).thenReturn(collection);
PowerMockito.when(collection.aggregate(anyList(),any())).thenReturn(iterable);
PowerMockito.when(iterable.iterator()).thenReturn(iterator);
PowerMockito.when(iterator.hasNext()).thenReturn(true,true,false);
PowerMockito.when(iterator.next()).thenReturn(user1,user2);
getAggregatedList(new User());
}
这将为您带来您期望的结果。