【问题标题】:return mocked object for function defined in stream.map为 stream.map 中定义的函数返回模拟对象
【发布时间】:2017-12-22 07:23:51
【问题描述】:

我需要模拟一个包含函数 F 的依赖类。

要测试的类:

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 sn-p:

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

测试类 sn-p:

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

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

【问题讨论】:

  • 你考虑过从字段注入改为构造函数注入吗?
  • 你为什么要嘲笑这个?只需返回Function

标签: unit-testing java-8 mockito junit4


【解决方案1】:

改变这一行:

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

到这里:

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

这应该可以解决您的问题(注意添加了 () )。

请注意,mockedDependentClass 必须是一个模拟,使用 @MockMockito.mock(....) 创建

【讨论】:

    猜你喜欢
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多