我在使用groovy中的模拟支持测试具有依赖性的协作时遇到了有趣的问题。我们有两个类(示例):
class Dependency {
void method() {
throw new OperationNotSupportedException()
}
}
class Dependent {
Dependency dependency
void useDependency() {
dependency.with { method() }
}
}
注意方法()在依赖项上的调用方式——它是在依赖项的“with”方法中完成的。
我需要在测试中模拟对method()的调用,所以我的第一次尝试是这样做:
class IgnoringWithTest {
@Test
void testWithMock() {
def depMock = new MockFor(Dependency)
Dependent dep = new Dependent()
depMock.demand.method { }
dep.dependency = depMock.proxyInstance()
dep.useDependency()
depMock.verify dep.dependency
}
}
不幸的是,这种“幼稚”的方法会在测试执行期间导致错误消息“此时不需要调用”with“。仍然需要1个对“method”的调用。“这很好,因为我们确实尝试使用()方法对依赖项进行调用。
我尝试通过添加下一行来忽略对with()方法的调用:
depMock.ignore('with')
在这之后,我没有收到关于with()方法调用的抱怨,但是结果发现使用demand声明的期望被忽略了。结果我得到了OperationNotSupportedException。
现在的问题是——如何在实现过程中,在传递给with()的闭包中调用方法(),而不产生问题?