Mockito / PowerMockito - 模拟一个接收Lambda表达式作为参数的方法

时间:2017-08-01 21:44:01

标签: mockito powermockito

我想模仿以下方法。但我没有找到使用#include <vector> #include <algorithm> using namespace std; int main() { vector<int> values{0, 10, 20, 30, 40, 50, 60, 70, 80, 90}; vector<size_t> IndexesToMove{2,4}; size_t NewIndex = 6; //check that your indices are sorted, non-empty, in the correct range, etc. // move one element in front of the next element to move // then move those two elements in front of the next element to move // ... auto it_next = values.begin() + IndexesToMove.front(); for(size_t i = 0; i < IndexesToMove.size() -1; i++) { auto it_first = it_next - i; it_next = values.begin() + IndexesToMove[i+1]; rotate(it_first, it_first + i + 1 , it_next); } // move the collected elements at the target position rotate(it_next - IndexesToMove.size() + 1, it_next + 1, values.begin() + NewIndex); } 的第二个参数的任何Mockito.Matchers

Java.util.Function

我正在寻找类似的东西:

public List<String> convertStringtoInt(List<Integer> intList,Function<Integer, String> intToStringExpression) {
        return intList.stream()
                .map(intToStringExpression)
                .collect(Collectors.toList());
    }

1 个答案:

答案 0 :(得分:2)

如果您只想模拟Function参数,则以下任何一个都可以工作:

Mockito.when(convertStringtoInt(Matchers.anyList(), Mockito.any(Function.class))).thenReturn(myMockedList);

Mockito.when(convertStringtoInt(Matchers.anyList(), Mockito.<Function>anyObject())).thenReturn(myMockedList);

给定一个类Foo,其中包含方法:public List<String> convertStringtoInt(List<Integer> intList,Function<Integer, String> intToStringExpression),以下测试用例通过:

@Test
public void test_withMatcher() {
    Foo foo = Mockito.mock(Foo.class);

    List<String> myMockedList = Lists.newArrayList("a", "b", "c");

    Mockito.when(foo.convertStringtoInt(Matchers.anyList(), Mockito.<Function>anyObject())).thenReturn(myMockedList);

    List<String> actual = foo.convertStringtoInt(Lists.newArrayList(1), new Function<Integer, String>() {
        @Override
        public String apply(Integer integer) {
            return null;
        }
    });

    assertEquals(myMockedList, actual);
}

注意:如果您确实想要调用和控制Function参数的行为,那么我认为您需要查看thenAnswer()