mockito 如何为Cosmos容器查询项编写Junit测试?

dnph8jn4  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(78)

我有一个要求,我需要为下面的代码段编写Junit测试。问题是我无法弄清楚如何创建Iterable<FeedResponse<T>>的实际虚拟示例,因为如果我传递Iterable<FeedResponse<T>>的模拟示例,那么下一步的for循环会抛出空指针异常,因为它试图遍历模拟示例并在其中找不到任何东西。下面给出的是来自实际类和测试方法的代码块。任何线索都将不胜感激。

实际类- for循环是问题

Iterable<FeedResponse<Employee>> feedResponseIterator = cosmosContainer
                        .queryItems(query, queryOptions, Employee.class)
                        .iterableByPage(continuationToken, pageSize);
for (FeedResponse<Employee> page : feedResponseIterator) {
                    }

测试方法-这种方法从for循环中抛出空指针,如上所述

@Mock
CosmosClientManager cosmosClientManager;

@Mock
CosmosContainer cosmosContainer;

@Mock
CosmosPagedIterable<Employee> page;
    
@Mock
Iterable<FeedResponse<Employee>> feedResponseIterator;

when(cosmosClientManager.getCosmosContainer(anyString())).thenReturn(cosmosContainer);
when(cosmosContainer.queryItems(anyString(), any(), eq(Employee.class))).thenReturn(page);
when(page.iterableByPage(any(), anyInt())).thenReturn(feedResponseIterator);
ibps3vxo

ibps3vxo1#

您的iterable不会存根它的任何方法,这意味着在它上面调用iterator()(这就是增强的for循环所做的)将得到一个null。要么stub所有必需的mock调用(iterator()然后返回一个适当的迭代器,或者stub迭代器上的所有重要方法...),要么修改代码以返回一个实际的CosmosPagedIterable示例。
请注意,您的字段名为feedResponseIterator,但它不是迭代器,而是Iterable(类上的一个接口,可以 * 返回 * 迭代器)
下面是一个如何使用真实的示例的示例:

@Mock
CosmosClientManager cosmosClientManager;

@Mock
CosmosContainer cosmosContainer;

@Mock
CosmosPagedIterable<Employee> page;

when(cosmosClientManager.getCosmosContainer(anyString())).thenReturn(cosmosContainer);
when(cosmosContainer.queryItems(anyString(), any(), eq(Employee.class))).thenReturn(page);

// define responses:
final List<FeedResponse<Employee>> = List.of(new FeedResponse<>(...), ...);
// the iterable returns an iterator for the predefined list:
final Iterable<FeedResponse<Employee>> iterable = responses::iterator; 
when(page.iterableByPage(any(), anyInt())).thenReturn(iterable);

如果可能的话,尝试将真实的行为推到调用链的更高位置。让容器返回页面的一个真实的CosmosPagedIterable示例。
这个相关的问题解释了为什么mock/stub collections/containers是有问题的:Why can non-empty mocked list not be looped?

相关问题