返回stream.map中定义的函数的模拟对象

时间:2017-12-22 07:23:52

标签: unit-testing java-8 mockito junit4

我需要模拟包含函数F<的依赖类。 R,C>。

要测试的课程:

class ClassToBeTested{
 @Autowired
 DependentClass dependentClass;

 public String doSomething(List<Person> list){
  ...
    list.stream().filter(p->p.getAge()>28).
    map(dependentClass.transformToEmployee).
    collect(Collectors.toList());
 ...
}

DependentClass片段:

public Function<R, C> transformToEmployee = new Function() {
        public C apply(R rrd) {
            C cc = new C();
            if (rrd == null) {
                return cc;
            } else {
                ccInfo.setName(rrd.getFirstName()+ rrd.getLastName());
                ccInfo.setAge(rrd.getAge);
                return cc;
            }
        }
};

测试类代码段

@Test
public void testDoSomething(){
...
   Function<R, C> info =new TestHelper().transformToEmployee;
   info.apply(r); 
   when(mockedDependentClass.transformToEmployee).thenReturn(info);
...
}

现在我在控制台中看到了这个exception when()需要一个必须是'模拟方法调用'的参数。

1 个答案:

答案 0 :(得分:0)

更改此行:

when(mockedDependentClass.transformToEmployee()).thenReturn(info);

到此:

()

这应解决您的问题(注意添加mockedDependentClass)。

请注意,@Mock必须是模拟,可以使用Mockito.mock(....)maxImageWidth = windowWidth - self.containerPadding.left - self.containerPadding.right - self.imageBorderWidth.left - self.imageBorderWidth.right - 20; maxImageHeight = windowHeight - self.containerPadding.top - self.containerPadding.bottom - self.imageBorderWidth.top - self.imageBorderWidth.bottom - 120;

创建