使用 Spock Java/Groovy 模拟 BiFunction

问题描述 投票:0回答:2

尝试模拟返回 BiFunction 的函数失败。
该函数看起来像

public interface myInterface { 
  Optional<BiFunction<Object, Object, Object>> myAwesomeFunc()
}

尝试像

那样嘲笑
def mockBiFunction = Mock(BiFunction)
mockMyInterface.myAwesomeFunc >> mockBiFunction 
mockBiFunction.apply(*_) >> mockReturnVal 

这会导致

No signature of method: com.sun.proxy.$Proxy49.apply() is applicable for argument types: (org.spockframework.lang.SpreadWildcard) values: [*_]
Possible solutions: apply(java.lang.Object, java.lang.Object), any(), any(groovy.lang.Closure), every(), tap(groovy.lang.Closure), every(groovy.lang.Closure)
groovy.lang.MissingMethodException: No signature of method: com.sun.proxy.$Proxy49.apply() is applicable for argument types: (org.spockframework.lang.SpreadWildcard) values: [*_]
Possible solutions: apply(java.lang.Object, java.lang.Object), any(), any(groovy.lang.Closure), every(), tap(groovy.lang.Closure), every(groovy.lang.Closure)

尝试过

mockBiFunction(*_) >> mockReturnVal

这也行不通。

编辑: 尝试过

mockBiFunction.apply(object1, object2) >> mockReturnVal

失败了

Cannot invoke method rightShift() on null object
java.lang.NullPointerException: Cannot invoke method rightShift() on null object

当我嘲笑它时,为什么它是空的??

testing groovy mocking java-11 spock
2个回答
1
投票

实际上,您的接口方法返回的是

Optional
,而不是
BiFunction
。更准确地说,它返回
Optional<BiFunction<Object, Object, Object>>
。因此,您的接口模拟在存根
Optional
时也需要返回
myAwesomeFunc()
。这就是 IMO 你的代码的错误。

这是我的看法:

package de.scrum_master.stackoverflow.q71602791

import spock.lang.Specification

import java.util.function.BiFunction

class BiFunctionMockTest extends Specification {
  def "mock BiFunction"() {
    given:
    def biFunction = Mock(BiFunction) {
      apply(*_) >> "dummy"
    }
    def myInterface = Mock(MyInterface) {
      myAwesomeFunc() >> Optional.of(biFunction)
    }
    def underTest = new MyInterfaceUser(myInterface: myInterface)

    expect:
    underTest.doSomething().get().apply("foo", "bar") == "dummy"
  }

  interface MyInterface {
    Optional<BiFunction<Object, Object, Object>> myAwesomeFunc()
  }

  static class MyInterfaceUser {
    MyInterface myInterface

    def doSomething() {
      myInterface.myAwesomeFunc()
    }
  }
}

0
投票

啊,看起来我所要做的就是使用一个函数作为

BiFunction
的模拟返回值,所以像下面这样的工作

def mockMyAwesomeFunc = abc -> mockReturnVal 
mockBiFunction.apply(object1, object2) >> mockMyAwesomeFunc

而不是做

mockBiFunction.apply(object1, object2) >> mockReturnVal

现在感觉自己真的很傻!!

编辑——更新答案以更准确地反映实际工作代码——这就是有效的

def mockBiFunction = Mock(BiFunction)
mockMyInterface.myAwesomeFunc >> Optional.of(mergeBiFunction)
mergeBiFunction.apply(_, _) >> (a, b) -> {
    return mockValue
}
© www.soinside.com 2019 - 2024. All rights reserved.