在没有 getter 的情况下模拟对象

问题描述 投票:0回答:1

我想模拟一个具有以下代码的函数 -

// Getting all ad insights objects from API
Connection<AdsInsights> insightsConnection = facebookClient.fetchConnection(
        adAccountId + "/insights",
        AdsInsights.class,
        Parameter.with("level", LEVEL_OF_INSIGHTS),
        Parameter.with("time_range", "{\"since\":\"" + startDate
                + "\",\"until\":\"" + endDate + "\"}"),
        Parameter.with("fields", fields),
        Parameter.with("time_increment", TIME_INCREMENT));

List<Row> rows = new ArrayList<>();

// Iterating over result pages
for (List<AdsInsights> insights : insightsConnection) {
    // Iterating over result of each page
    for (AdsInsights insight : insights) {

我无法弄清楚如何模拟

insightsConnection
对象。

我试着像-

那样嘲笑它
when(insightsConnectionMock.getData()).thenReturn(insightsList);

但这似乎不起作用,迭代开始时我仍然遇到空指针异常。

P.S 这些对象来自

restFb
图书馆

mocking mockito powermockito restfb
1个回答
0
投票

Java for-each 循环只是迭代器的语法糖。

因此:

for (List<AdsInsights> insights : insightsConnection) {
}

被编译器扩展为:

for (Iterator<List<AdsInsights>> it = insightsConnection.iterator(); it.hasNext();) {
    List<AdsInsights> insights = it.next();
}

参见https://restfb.com/documentation/:

Connection 对象实现

Iterable
接口。

© www.soinside.com 2019 - 2024. All rights reserved.