scala ScalaMock模拟通用Java接口重载方法
我试图模拟Java通用接口,该接口使用不同数量的参数重载方法。 接口代码为:
import java.util.concurrent.Callable;
public interface GOInterface<T> {
void send(T record);
void send(T record, Callable<T> onComplete);
}
我尝试使用onComplete功能模拟发送,如下所示:
导入java。util。同时发生的可调用
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}
class JavaInterfaceTest extends FlatSpec with Matchers with MockFactory {
behavior of "scalamock"
it should "mock java generic interface with overloaded method (with different number of parameters)" in {
var result = ""
val m = mock[GOInterface[String]]
(m.send(_: String, _: Callable[String])).expects(*, *)
.onCall{ case(s: String, c: Callable[String]) => c.call()}.once
m.send("hello", new Callable[String] {
override def call(): String = {result = "world"; result}
})
result should be("world")
}
it should "mock java generic interface with overloaded method (with different number of parameters) 2" in {
var result = ""
val m = mock[GOInterface[String]]
(m.send(_: String)).expects(*).once
m.send("hello")
result should be("")
}
}
我从编译器中得到的错误是:
error: value expects is not a member of (String, java.util.concurrent.Callable[String]) => Unit
[ERROR] (m.send(_: String, _: Callable[String])).expects(*, *)
[ERROR] ^
error: value expects is not a member of String => Unit
[ERROR] (m.send(_: String)).expects(*).once
[ERROR]
通过查看ScalaMock git上的不同示例,我可以看到没有任何测试可以检查具有不同参数计数的重载方法的泛型接口
我的依赖项是:
<dependency>
<groupId>org.scalamock</groupId>
<artifactId>scalamock-scalatest-support_2.11</artifactId>
<version>3.6.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.scalamock</groupId>
<artifactId>scalamock-core_2.11</artifactId>
<version>3.6.0</version>
<scope>test</scope>
</dependency>
同时,我在ScalaMock repo中创建了一个bug
# 1 楼答案
首先,我建议升级到ScalaMock的最新版本,但泛型和重载的极端情况可能也存在
为了解决这个问题,在很多情况下,先锁定类型,然后创建一个模拟:
# 2 楼答案
我设法克服了这个问题。不是以最干净的方式,而是它的工作方式。 正如@PhilippM建议的那样,我需要修复类型,但不幸的是,这还不够,我需要创建一个虚拟类。 以下是对我有效的解决方案:
我觉得这有点难看,当需要模拟更复杂的接口时,这可能是最糟糕的,但我希望它能帮助其他人