状态切换
从录制状态切换到回放状态,即将MockControl对象中的state属性从RecordState对象更改为ReplayState对象
MockControl类的Replay方法
publicvoid replay() {
try {
/*
* RecordState对象在切换前,会检查是否还有未添加到behavior对象中的预设值
* 如果有就添加到MocksBehavior对象中
*/
state.replay();
/*
* 切换状态,这里可以再次了解到behavior保存着所有录制数据
*/
state = newReplayState(behavior);
LastControl.reportLastControl(null);
} catch (finalRuntimeExceptionWrapper e) {
throw(RuntimeException) e.getRuntimeException().fillInStackTrace();
}
}
回放过程
时序图
当调用mock对象的方法时,如果方法不是要过滤的(equals、hashcode等)方法,最终会方法会通过MocksBehavior对象的addActual方法来查找到对应的返回结果。MocksBehavior查找对应结果的时序图如下:
MocksBehavior类的addActual方法(部分代码)
final int initialPosition =position;
while (position <behaviorLists.size()) {
final Result result =behaviorLists.get(position).addActual(actual);
if (result != null) {
return result;
}
if(!behaviorLists.get(position).verify()) {
break;
}
position++;
}
/*
* 当设定预期结果使用andStubReturn方法时,在MocksBehavior对象中也会保存一份
* 当mock对象调用函数调用次数超过预定次数时,就会用MocksBehavior对象中保存的值
*/
Result stubOrNice =getStubResult(actual);
/*
* 如果mock对象为nice类型时,找不到对应的结果值时返回null
*/
if (stubOrNice == null&& nice) {
stubOrNice =Result.createReturnResult(RecordState.emptyReturnValueFor(actual.getMethod().getReturnType()));
}
int endPosition = position;
// Do not move the cursor incase of stub, nice or error
position = initialPosition;
if (stubOrNice != null) {
actual.validateCaptures();
actual.clearCaptures();
return stubOrNice;
}