多次调用可迭代实现的模拟拆分器?

时间:2018-07-04 08:20:25

标签: java unit-testing mockito java-stream

我在模拟Iterable类并结合调用spliterator()时遇到问题。一次调用spliterator时一切正常,但是第二次调用不返回任何值。

由于模拟总是返回相同的Spliterator实例,因此我假设状态未重置。有办法吗?

这是我能给的最小例子

通话mapStringToHash是现实生活中的自由人,无法更改。 MyIterable也不受我控制。

package net.test;

import static org.hamcrest.CoreMatchers.is;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.MatcherAssert.assertThat;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class SpliteratorTest {

    class MyIterable<T> implements Iterable<T> {

        private List<T> list;

        MyIterable(List<T> list) {
            this.list = new ArrayList<>(list);
        }

        @Override
        public Iterator<T> iterator() {
            return list.iterator();
        }

        @Override
        public Spliterator<T> spliterator() {
            return list.spliterator();
        }
    }

    // this a library method
    private Stream<Integer> mapStringToHash(final MyIterable<String> myIterable) {
        return StreamSupport.stream(myIterable.spliterator(), false).map(String::hashCode);
    }

    @Test
    public void testSeveralSpliteratorCalls() {
        MyIterable myIterable = givenMyIterableMock("a", "b", "c");

        Stream<Integer> myIterableHash1 = mapStringToHash(myIterable);
        assertThat(myIterableHash1.count(), is(3L));


        Stream<Integer> myIterableHash2 = mapStringToHash(myIterable);
        assertThat(myIterableHash2.count(), is(3L));
    }

    private MyIterable givenMyIterableMock(String... values) {
        MyIterable myIterable = mock(MyIterable.class);

        Spliterator myIterableSpliterator = Arrays.stream(values)
                .collect(toList())
                .spliterator();
        doReturn(myIterableSpliterator).when(myIterable).spliterator();
        return myIterable;
    }
}

1 个答案:

答案 0 :(得分:2)

事实证明,它不像我想的那样绕开。可以使用自定义的Answer实现来实现,但是由于Answer是一个功能接口,因此满足以下条件:

Mockito.when(myIterable.spliterator()).then(invocation -> Arrays.spliterator(values));