Spock 模拟多个接口

Spock mock multiple interfaces

我有一个 Jax-WS Webservice 调用,它包含在 class 中,我需要使用 spock 对其进行测试。 Web 服务调用的实现是在我无法更改的 superclass 中完成的。我更愿意重新设计并摆脱继承,但我不能那样做。

对于我的单元测试,我不想模拟网络服务。创建端口的代码如下所示:

MyPortType client = createServiceClient(); //inherited from superclass, needs to be mocked
(BindingProvider) bp = (BindingProvider) client;

转换为 BindingProvider 对于 JAX-WS 总是安全的,所以这不是问题。但是我需要模拟 createServiceClient() 方法,我需要它 return 一个同时实现 MyPortTypeBindingProvider.

的模拟

这是我目前得到的:

MyPortType port = Mock(MyPortType) as BindingProvider
port.myMethod(_ as MyType) >> Mock(MyResponse)

但我得到这个例外:

java.lang.AbstractMethodError: Receiver class $Proxy541_groovyProxy does not define or inherit an implementation of the resolved method 'abstract MyResponse myMethod(MyType)' of interface MyPortType.

我怀疑我还在以错误的方式定义 MyPortType Mock,但我想不通。

有人试过这种东西吗?

EDIT:这两个 return 都是真的,所以看起来 class 的模拟有效,但是方法的模拟没有:

port instanceof MyPortType
port instanceof BindingProvider

您想使用 Mock(MyPortType, additionalInterfaces: [BindingProvider]),即 A la Carte Mocks。 但是,有一个 open issue 阻止定义附加接口方法的响应,因此它只会通过 instanceof 检查。作为解决方法,您可以定义一个扩展两个接口的测试接口。

interface TestPortType extends MyPortType, BindingProvider {}
// ...
TestPortType port = Mock(TestPortType)