//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);
...
延伸阅读
文章来源于领测软件测试网 https://www.ltesting.net/