2017-08-01 574 views
0

我想模拟以下方法。但是我没有找到任何使用Java.util.Function的第二个参数Mockito.MatchersMockito/PowerMockito - 模拟接收Lambda表达式作为参数的方法

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) 

回答

2

如果你只想嘲笑功能参数,那么下面的任一会的工作:

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); 
} 

注意:如果你真的想要调用和控制函数参数的行为,那么我认为你需要看看thenAnswer()

+0

@Glictch。这工作完美。辉煌! 'Mockito.when(convertStringtoInt(Matchers.anyList(),Mockito。 anyObject()))。然后返回(myMockedList);' – naga1990

相关问题