选择显示字体大小

单元测试中的伪对象

单元测试中的伪对象

作者:lu jian

译者:xmatrix


版权声明:任何获得matrix授权的网站,转载时请务必以超链接形式标明文章原始出处和作者信息及本声明
作者:lu jian;xmatrix
原文地址: http://www.onjava.com/pub/a/onjava/2005/01/12/mocquer.html
中文地址:http://www.matrix.org.cn/resource/article/43/43901_mock_unit.html
关键词: mock  unit test

在单元测试的策略中伪对象被广泛使用。他从测试中分离了外部的不需要的因素并且帮助开发人员专注于被测试的功能。

easymock是一个在这方面很有名的工具,可以在运行时为给定的接口创建伪对象。伪对象的行为可以在测试用例中的执行测试代码之前被定义。easymock基于java.lang.reflect.proxy,他可以根据给定的接口创建动态代理类或者对象。但因为使用proxy使得他有一个天生的缺陷:只能创建基于接口的伪对象。

mocquer是一个类似的工具,但他扩展了easymock的功能能够支持创建类的伪对象。

mocquer介绍
mocquer基于dunamis项目,被用来为特定的类或接口生成动态代理类或对象。为方便使用,他遵循easymock的类和方法的命名规范,只是在内部使用不同的实现方法。

mockcontrol是mocquer项目中最重要的类。他被用来控制伪对象的生命周期和行为定义。这个类中有四类方法。

1、生命周期控制方法:
·public void replay();
·public void verify();
·public void reset();

伪对象在他的生命周期中有三种状态:准备态、工作态、验证态。图1显示了伪对象的生命周期。


figure 1. mock object life cycle

刚开始,伪对象处于准备态,他的表现行为可以在这里定义。replay()将改变伪对象的状态为工作态。在这个状态中所有伪对象的方法调用将会遵循在准备态下定义的行为。在verify()调用后,伪对象就处于验证态。mockcontrol会比较伪对象的预定义行为与实际行为是否匹配。匹配规则依赖于使用的mockcontrol类型,这个会在稍后解释。开发人员可以在需要时调用replay()来重现预定义的行为。而任何状态下调用reset()将会清除状态历史并重置为初始的准备态。

2、工厂方法
·public static mockcontrol createnicecontrol(...);
·public static mockcontrol createcontrol(...);
·public static mockcontrol createstrictcontrol(...);

mocquer提供了三种mockcontrol:宽松的,普通的和严格的。开发人员可以在自己的测试用例中根据测试的内容(测试点)和测试的执行方式(测试策略)选择相应的mockcontrol。宽松的mockcontrol是最随意的,他不关心伪对象中方法调用的顺序,甚至未预期的方法调用,只是返回一个缺省值(依赖于方法的返回值)。普通的mockcontrol比宽松的mockcontrol严格些,未预期的方法调用会导致assertionfailederror异常。严格的mockcontrol是最严格的,如果伪对象在工作态下方法调用的顺序与准备态的不同,就会抛出assertionfailederror异常。下表显示了三种不同mockcontrol的区别。



下面是每一个工厂方法的两个不同版本。
 public static mockcontrol createxxxcontrol(class clazz);
public static mockcontrol createxxxcontrol(class clazz,
    class[] argtypes, object[] args);


如果类是作为接口来模拟的或者他有一个公共或保护的缺省构造函数,则第一个版本的方法会被使用。否则第二个版本会被用来定义标识和提供参数给期望的构造函数。例如,假设
classwithnodefaultconstructor是一个没有缺省构造函数的类:
    public class classwithnodefaultconstructor {
      public classwithnodefaultconstructor(int i) {
        ...
      }
      ...
    }


·伪对象获取方法
public object getmock();

每一个mockcontrol包含一个生成的伪对象的引用。开发人员可以使用这个方法取得伪对象并且转换为实际的对象类型。

 //get mock control
    mockcontrol control = mockcontrol.createcontrol(foo.class);
    //get the mock object from mock control
    foo foo = (foo) control.getmock();


·行为定义方法
public void setreturnvalue(... value);
public void setthrowable(throwable throwable);
public void setvoidcallable();
public void setdefaultreturnvalue(... value);
public void setdefaultthrowable(throwable throwable);
public void setdefaultvoidcallable();
public void setmatcher(argumentsmatcher matcher);
public void setdefaultmatcher(argumentsmatcher matcher);

mockcontrol允许开发人员定义伪对象的每一个方法的行为。当他在准备态时,开发人员可以调用伪对象的方法。首先规定哪一个调用方法的行为需要被定义。然后开发人员可以使用行为定义的方法之一来定义行为。例如,看一下下面的foo类:
 //foo.java
    public class foo {
      public void dummy() throw parseexception {
        ...
      }
      public string bar(int i) {
        ...
      }
      public boolean issame(string[] strs) {
        ...
      }
      public void add(stringbuffer sb, string s) {
        ...
      }
    }


伪对象的行为可以按照下面的方式来定义:

//get mock control
    mockcontrol control = mockcontrol.createcontrol(foo.class);
    //get mock object
    foo foo = (foo)control.getmock();
    //begin behavior definition

    //specify which method invocation's behavior
    //to be defined.
    foo.bar(10);
    //define the behavior -- return "ok" when the
    //argument is 10
    control.setreturnvalue("ok");
    ...

    //end behavior definition
    control.replay();
    ...


mockcontrol中超过50个方法是行为定义方法。他们可以如下分类。

o        setreturnvalue()
这些方法被用来定义最后的方法调用应该返回一个值作为参数。这儿有7个使用原始类型作业参数的`setreturnvalue()方法,如setreturnvalue(int i)或setreturnvalue(float f)。setreturnvalue(object obj)被用来满足那些需要对象作为参数的方法。如果给定的值不匹配方法的返回值,则抛出assertionfailederror异常。
当然也可以在行为中加入预期调用的次数。这称为调用次数限制。

      mockcontrol control = ...
      foo foo = (foo)control.getmock();
      ...
      foo.bar(10);
      //define the behavior -- return "ok" when the
      //argument is 10. and this method is expected
      //to be called just once.
      setreturnvalue("ok", 1);
      ...


上面的代码段定义了bar(10)方法只能被调用一次。如果提供一个范围又会怎么样呢?
      ...
      foo.bar(10);
      //define the behavior -- return "ok" when the
      //argument is 10. and this method is expected
      //to be called at least once and at most 3
      //times.
      setreturnvalue("ok", 1, 3);
      ...

      
现在bar(10)被限制至少被调用一次最多3次。更方便的是range已经预定义了一些限制范围。
      ...
      foo.bar(10);
      //define the behavior -- return "ok" when the
      //argument is 10. and this method is expected
      //to be called at least once.
      setreturnvalue("ok", range.one_or_more);
      ...




range.one_or_more是一个预定义的range实例,这意味着方法应该被调用至少一次。如果setreturnvalue()中没有定义调用次数限制,如setreturnvalue("hello"),range.one_or_more被认为是缺省值。还有两个预定义的range实例,range.one(就一次)和range.zero_or_more(对调用次数没有限制)。
这儿还有一个特定的设置返回值的方法:setdefaultreturnvalue()。他将代替方法的参数值作为返回值,缺省的调用次数限制为range.one_or_more。这被称为方法参数值敏感性。
      ...
      foo.bar(10);
      //define the behavior -- return "ok" when calling
      //bar(int) despite the argument value.
      setdefaultreturnvalue("ok");
      ...
    
  

o        setthrowable

setthrowable(throwable throwable)被用来定义方法调用异常抛出的行为。如果给定的throwable不匹配方法的异常定义,则assertionfailederror会被抛出。调用次数的限制与方法参数值敏感性是一致的。
      ...
      try {
        foo.dummy();
      } catch (exception e) {
        //skip
      }
      //define the behavior -- throw parseexception
      //when call dummy(). and this method is expected
      //to be called exactly once.
      control.setthrowable(new parseexception("", 0), 1);
      ...

      
o        setvoidcallable()
setvoidcallable()被用于没有返回值的方法。调用次数的限制与方法参数值敏感性是一致的。
      ...
      try {
        foo.dummy();
      } catch (exception e) {
        //skip
      }
      //define the behavior -- no return value
      //when calling dummy(). and this method is expected
      //to be called at least once.
      control.setvoidcallable();
      ...

      
o        set argumentsmatcher
在工作态时,mockcontrol会在伪对象的方法被调用时搜索预定义的行为。有三个因素会影响搜索的标准:方法标识,参数值和调用次数限制。第一和第三个因素是固定的。第二个因素可以通过参数值敏感性来忽略。更灵活的是,还可以自定义参数值匹配规则。setmatcher()可以通过argumentsmatcher在准备态时使用。
      public interface argumentsmatcher {
        public boolean matches(object[] expected,
                               object[] actual);
      }

      
argumentsmatcher唯一的方法matches()包含两个参数。一个是期望的参数值数组(如果参数值敏感特性应用时为null)。另一个是实际参数值数组。如果参数值匹配就返回真。
      ...
      foo.issame(null);
      //set the argument match rule -- always match
      //no matter what parameter is given
      control.setmatcher(mockcontrol.always_matcher);
      //define the behavior -- return true when call
      //issame(). and this method is expected
      //to be called at least once.
      control.setreturnvalue(true, 1);
      ...


mockcontrol中有三个预定义的argumentsmatcher实例。mockcontrol.always_matcher在匹配时始终返回真而不管给什么参数值。mockcontrol.equals_matcher会为参数值数组的每一个元素调用equals()方法。mockcontrol.array_matcher与mockcontrol.equals_matcher基本一致,除了他调用的是arrays.equals()。当然,开发人员可以实现自己的argumentsmatcher。
然而自定义的argumentsmatcher有一个副作用是需要定义方法调用的输出参数值。
      ...
      //just to demonstrate the function
      //of out parameter value definition
      foo.add(new string[]{null, null});
      //set the argument match rule -- always
      //match no matter what parameter given.
      //also defined the value of out param.
      control.setmatcher(new argumentsmatcher() {
        public boolean matches(object[] expected,
                               object[] actual) {
           ((stringbuffer)actual[0])
                              .append(actual[1]);
           return true;
        }
      });
      //define the behavior of add().
      //this method is expected to be called at
      //least once.
      control.setvoidcallable(true, 1);
      ...

      
setdefaultmatcher()设置mockcontrol的缺省argumentsmatcher实例。如果没有特定的argumentsmatcher,缺省的argumentsmatcher会被使用。这个方法应该在任何方法调用行为定义前被调用。否则,会抛出assertionfailederror异常。
      //get mock control
      mockcontrol control = ...;
      //get mock object
      foo foo = (foo)control.getmock();

      //set default argumentsmatcher
      control.setdefaultmatcher(
                     mockcontrol.always_matcher);
      //begin behavior definition
      foo.bar(10);
      control.setreturnvalue("ok");
      ...


如果没有使用setdefaultmatcher(),mockcontrol.array_matcher就是缺省的argumentsmatcher。

一个例子
下面是一个在单元测试中演示mocquer用法的例子,假设存在一个类ftpconnector。

package org.jingle.mocquer.sample;

import java.io.ioexception;
import java.net.socketexception;

import org.apache.commons.net.ftp.ftpclient;

public class ftpconnector {
    //ftp server host name
    string hostname;
    //ftp server port number
    int port;
    //user name
    string user;
    //password
    string pass;

    public ftpconnector(string hostname,
                        int port,
                        string user,
                        string pass) {
        this.hostname = hostname;
        this.port = port;
        this.user = user;
        this.pass = pass;
    }

    /**
     * connect to the ftp server.
     * the max retry times is 3.
     * @return true if succeed
     */
    public boolean connect() {
        boolean ret = false;
        ftpclient ftp = getftpclient();
        int times = 1;
        while ((times <= 3) && !ret) {
            try {
                ftp.connect(hostname, port);
                ret = ftp.login(user, pass);
            } catch (socketexception e) {
            } catch (ioexception e) {
            } finally {
                times++;
            }
        }
        return ret;
    }

    /**
     * get the ftpclient instance
     * it seems that this method is a nonsense
     * at first glance. actually, this method
     * is very important for unit test using
     * mock technology.
     * @return ftpclient instance
     */
    protected ftpclient getftpclient() {
        return new ftpclient();
    }
}


connect()方法尝试连接ftp服务器并且登录。如果失败了,他可以尝试三次。如果操作成功返回真。否则返回假。这个类使用org.apache.commons.net.ftpclient来生成一个实际的连接。他有一个初看起来毫无用处的保护方法getftpclient()。实际上这个方法对使用伪技术的单元测试是非常重要的。我会在稍后解释。
一个junit测试实例ftpconnectortest被用来测试connect()方法的逻辑。因为我们想要将单元测试环境从其他因素中(如外部ftp服务器)分离出来,因此我们使用mocquer来模拟ftpclient。

package org.jingle.mocquer.sample;

import java.io.ioexception;

import org.apache.commons.net.ftp.ftpclient;
import org.jingle.mocquer.mockcontrol;

import junit.framework.testcase;

public class ftpconnectortest extends testcase {

    /*
     * @see testcase#setup()
     */
    protected void setup() throws exception {
        super.setup();
    }

    /*
     * @see testcase#teardown()
     */
    protected void teardown() throws exception {
        super.teardown();
    }

    /**
     * test ftpconnector.connect()
     */
    public final void testconnect() {
        //get strict mock control
        mockcontrol control =
             mockcontrol.createstrictcontrol(
                                ftpclient.class);
        //get mock object
        //why final? try to remove it
        final ftpclient ftp =
                    (ftpclient)control.getmock();

        //test point 1
        //begin behavior definition
        try {
            //specify the method invocation
            ftp.connect(&quot;202.96.69.8&quot;, 7010);
            //specify the behavior
            //throw ioexception when call
            //connect() with parameters
            //&quot;202.96.69.8&quot; and 7010. this method
            //should be called exactly three times
            control.setthrowable(
                            new ioexception(), 3);
            //change to working state
            control.replay();
        } catch (exception e) {
            fail(&quot;unexpected exception: &quot; + e);
        }

        //prepare the instance
        //the overridden method is the bridge to
        //introduce the mock object.
        ftpconnector inst = new ftpconnector(
                                  &quot;202.96.69.8&quot;,
                                  7010,
                                  &quot;user&quot;,
                                  &quot;pass&quot;) {
            protected ftpclient getftpclient() {
                //do you understand why declare
                //the ftp variable as final now?
                return ftp;
            }
        };
        //in this case, the connect() should
        //return false
        assertfalse(inst.connect());

        //change to checking state
        control.verify();

        //test point 2
        try {
            //return to preparing state first
            control.reset();
            //behavior definition
            ftp.connect(&quot;202.96.69.8&quot;, 7010);
            control.setthrowable(
                           new ioexception(), 2);
            ftp.connect(&quot;202.96.69.8&quot;, 7010);
            control.setvoidcallable(1);
            ftp.login(&quot;user&quot;, &quot;pass&quot;);
            control.setreturnvalue(true, 1);
            control.replay();
        } catch (exception e) {
            fail(&quot;unexpected exception: &quot; + e);
        }

        //in this case, the connect() should
        //return true
        asserttrue(inst.connect());

        //verify again
        control.verify();
    }
}


这里创建了一个严格的mockobject。伪对象变量有一个final修饰符因为变量会在匿名内部类中使用,否则有产生编译错误。
在这个测试方法中包含两个测试点。第一个是什么时候ftpclient.connect()始终抛出异常,也就是说ftpclient.connect()返回假。

try {
    ftp.connect(&quot;202.96.69.8&quot;, 7010);
    control.setthrowable(new ioexception(), 3);
    control.replay();
} catch (exception e) {
    fail(&quot;unexpected exception: &quot; + e);
}


mockcontrol在调用伪对象connect()方法传入参数202.96.96.8作为主机地址及7010作为端口号时会抛出ioexception异常。这个方法调用预期执行三次。在行为定义后,replay()改变伪对象状态为工作态。这里的try/catch块包裹着ftpclient.connect()的定义,因为他定义了抛出ioexception异常。

ftpconnector inst = new ftpconnector(&quot;202.96.69.8&quot;,
                                     7010,
                                     &quot;user&quot;,
                                     &quot;pass&quot;) {
    protected ftpclient getftpclient() {
        return ftp;
    }
};


上面的代码创建一个重写了getftpclient()方法的ftpconnector实例。这样就桥接了创建的伪对象给用来测试的目标。

assertfalse(inst.connect());


在这里预期connect()应该返回假。
control.verify();

最后,改变伪对象到验证态。
第二个测试点是什么时候ftpclient.connect()前两次抛出异常而第三次会成功,这时ftpclient.login()当然也是成功的,这意味着ftpconnector.connect()会返回真。
这个测试点是在前一个测试点之后运行,因此需要将mockobject的状态通过reset()重新置为准备态。


总结
模拟技术将测试的对象从其他外部因素中分离出来。在junit框架中集成模拟技术使得单元测试更加简单和优雅。easymock是一个好的伪装工具,可以为特定接口创建伪对象。在dunamis协助下,mocquer扩展了easymock的功能,他可以为类创建伪对象。这篇文章简单介绍了mocquer在单元测试中的使用。更多信息可以参考下面的参考资料。

参考资料
&middot;mocquer项目:
&middot;下载这篇文章的示例代码。
&#8226;dunamis项目
&#8226;一篇关于动态代理的文章:&ldquo;动态代理及其应用&rdquo;
&#8226;easymock: www.easymock.org
&#8226;junit: www.junit.org

关于作者:
lu jian是一个高级java架构及开发工程师,拥有四年的java开发经验。


 


关键字 本文所属关键字

相关 与本文相关文章

分类 所有文章关键字导航

源码编程相关

Java   Asp   PHP   .Net   XML   C/C++   CGI   VB   Jsp   J2ee   J2se   J2me   EJB   Servlet   Tomcat   Resin   Struts   Weblogic   Eclipse   ANT   GUI   JMS   Web servise   IDEA   Webphere   Hibernate   Spring   Jboss   Applet   Swing   Socket   Javamail   Perl   Ajax   P2P   安全   模式   框架   测试   开源   游戏

SQL数据库相关

My-SQL   Ms-SQL   Access   DB2   Oracle   Sybase   SQLserver   索引   存储过程   加密   数据库   分页   视图  

手机无线相关

3G   Wap   CDMA   GRPS   GSM   IVR   彩信   短信   无线   增值业务

网页设计制作相关

HTML   CSS   网页配色   网页特效   Javascript   VBscript   Dreamweaver   Frontpage   JS   Web   网站设计

网站建设推广相关

建站经验   网站优化   网站排名   推广   Alexa

操作系统/服务器相关

Windows XP   Windows 2000   Windows 2003   Windows Me   Windows 9.x   Linux   UNIX   注册表   操作系统   服务器   应用服务器

图形图像多媒体相关

Photoshop   Fireworks   Flash   Coreldraw   Illustrator   Freehand   Photoimpact   多媒体   图形图像

标准 网站致力的规范

Valid CSS!

无不良内容,无不良广告,无恶意代码

Valid XHTML 1.0 Transitional

creativecommons