gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:32:08 24 4
gpt4 key购买 nike

我想模拟以下方法。但我没有找到任何 Mockito.Matchers对于使用 Java.util.Function 的第二个参数.

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

我正在寻找这样的东西:
Mockito.when(convertStringtoInt(Matchers.anyList(),Matchers.anyFunction()).thenReturn(myMockedList)

最佳答案

如果您只想模拟 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() .

关于Mockito/PowerMockito - 模拟接收 Lambda 表达式作为参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45448153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com