easymock源码学习笔记(3)--回放

状态切换

从录制状态切换到回放状态,即将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;

        }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值