【问题标题】:Mock for loop with interface带接口的模拟循环
【发布时间】:2016-06-01 16:44:44
【问题描述】:

我有这个包含接口的java代码。

ILocation<ILocation> contactLocations = fileSystem.getContactLocations();
for (ILocation location : contactLocations) {
    location.getType();
    ...
}

public interface ILocation{
    String getName();
    ...
}

public interface ILocationS<T extends ILocation> extends IListCollectionWrapper<T> {
    ...
}

public abstract interface IListCollectionWrapper<E>extends ICollectionWrapper<E>{
    public abstract List<E> getAsList();
}

ILocation<ILocation> contactLocations = fileSystem.getContactLocations();
for (ILocation locations : contactLocations) {
    ...
}

我使用 Mockito 并尝试测试 for 循环的内容。

Iterator<ILocation> mockIterator = mock(Iterator.class);
Mockito.when(locations.iterator()).thenReturn(mockIterator);

Mockito.when(mockIterator.next()).thenReturn(location);

Mockito.when(location.getType()).thenReturn("test");

我从不进入 de for 循环

【问题讨论】:

  • 您是否编写了自己的迭代器?如果是这样,您可以分享该代码吗?如果没有,您能否模拟 fileSystem.getContactLocations() 以返回正确的 ILocation 对象,这样您就不必模拟迭代器?

标签: junit mockito powermock


【解决方案1】:

你没有正确地模拟 Iterator 的另一个重要方法,hasNext。默认情况下,Mockito 将为所有布尔类型的方法返回 false,因此 hasNext 将始终为 false,您将永远不会进入 for 循环。

这是一个很好的理由,不要像大多数 Iterables 那样模拟数据对象;使用真实的东西,或者创建一个new ArrayList&lt;ILocation&gt;,填充它,然后让你的模拟返回yourArrayList.iterator()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-05
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    相关资源
    最近更新 更多