谈谈单元测试中的测试桩实践 (2)

首先定义一个Clock接口。并为Clock实现两个具体类,一个是NtpClockWrapper,顾名思义其实就是实现了ClockNtpClock,另一个是SystemClock,它就提供系统当前时间作为标准时间。

 

package shannon.demo;

 

/**

 * <code>Clock</code> is an interface for all the clock to provide time.

 * @author Shannon Qian

 */

public interface Clock {

    /**Returns the time in millusecond.

     * @return - the time in millusecond

     */

    public long getTime();

}

 

同时,我们定义一个UnitTestFirewall类,维护一个debugging标记。并提供一个getClock()类工厂方法,返回Clock对象。

 

package shannon.demo;

 

import thirdparty.any.NtpClock;

 

/**

 * <code>UnitTestFirewall</code> is the facility to

 * ease unit test

 * @author Shannon Qian

 */

public final class UnitTestFirewall {

    private static boolean debugging=false;

 

    /**Returns true if it's in debugging mode, else false.

     * @return the debugging

     */

    public static boolean isDebugging() {

       return debugging;

    }

 

    /**Sets Debugging flag as true if it's time to unit test.

     * @param on - the debugging to set, true for on and false

     * for off

     */

    public static void setDebugging(boolean on) {

       UnitTestFirewall.debugging = on;

    }

   

    private final static NtpClock _ntpClock=new NtpClock();

   

    private static class NtpClockWrapper implements Clock {

       public long getTime() {

           return _ntpClock.getTime();

       }

    }

   

    private static class SystemClock implements Clock {

       public long getTime() {

           return System.currentTimeMillis();

       }

    }

   

    private static SystemClock sysClock = null;

    private static NtpClockWrapper ntpClock = null;

   

    /**Returns the Clock instance for <code>SystemTimeSynchronizer

     * </code>'s invocation.

     * @return - Clock instance

     */

    public static Clock getClock() {

           if(debugging) {

              if(sysClock == null)

                  sysClock = new SystemClock();

              return sysClock;

           }

           else {

              if(ntpClock == null)

                  ntpClock = new NtpClockWrapper();

              return ntpClock;

           }

    }

}

 

(未完待续)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值