Stubbing 是让协做者以某种方式响应方法调用的行为。在对方法进行存根化时,不关心该方法的调用次数,只是但愿它在被调用时返回一些值,或者执行一些反作用。
subscriber.receive(_) >> "ok"
| | | |
| | | response generator
| | argument constraint
| method constraint
target constraint
如:subscriber.receive(_) >> "ok" 意味,无论什么实例,什么参数,调用 receive 方法皆返回字符串 ok
返回固定值
使用 >> 操做符,返回固定值
subscriber.receive(_) >> "ok"
返回值序列
返回一个序列,迭代且依次返回指定值。以下所示,第一次调用返回 ok,第二次调用返回 error,以此类推
subscriber.receive(_) >>> ["ok", "error", "error", "ok"]
动态计算返回值
subscriber.receive(_) >> { args -> args[0].size() > 3 ? "ok" : "fail" }
subscriber.receive(_) >> { String message -> message.size() > 3 ? "ok" : "fail" }
产生反作用
subscriber.receive(_) >> { throw new InternalError("ouch") }
链式响应
subscriber.receive(_) >>> ["ok", "fail", "ok"] >> { throw new InternalError() } >> "ok"