在学习Expectations(API:Expectations)时 ,在new Expectations{{}}代码中,返回的结果都比较简单。就是一个单一的对象。可是有时,这个返回的结果,可能是需要经历一些业务逻辑计算后,才知道返回什么的,此时,我们就需要定制返回结果了。
还是上例子吧。
还是以上文打招呼的例子来说。
//打招呼的接口
public interface ISayHello {
// 性别:男
int MALE = 0;
// 性别:女
int FEMALE = 1;
/**
* 打招呼
*
* @param who 向谁说
* @param gender 对方的性别
* @return 返回打招呼的内容
*/
String sayHello(String who, int gender);
/**
* 向多个人打招呼
*
* @param who 向谁说
* @param gender 对方的性别
* @return 返回向多个人打招呼的内容
*/
List<String> sayHello(String[] who, int[] gender);
}
public class SayHello implements ISayHello {
@Override
public String sayHello(String who, int gender) {
// 性别校验
if (gender != FEMALE) {
if (gender != MALE) {
throw new IllegalArgumentException("illegal gender");
}
}
// 根据不同性别,返回不同打招呼的内容
switch (gender) {
case FEMALE:
return "hello Mrs " + who;
case MALE:
return "hello Mr " + who;
default:
return "hello " + who;
}
}
@Override
public List<String> sayHello(String[] who, int[] gender) {
// 参数校验
if (who == null || gender == null) {
return null;
}
if (who.length != gender.length) {
throw new IllegalArgumentException();
}
//把向每个人打招呼的内容,保存到result中。
List<String> result = new ArrayList<String>();
for (int i = 0; i < gender.length; i++) {
result.add(this.sayHello(who[i], gender[i]));
}
return result;
}
}
测试时,如果想根据入参,返回结果的内容,怎么办呢?
// 定制返回结果
public class DeletgateResultTest {
@SuppressWarnings("rawtypes")
@Test
public void testDelegate() {
new Expectations(SayHello.class) {
{
SayHello instance = new SayHello();
instance.sayHello(anyString, anyInt);
result = new Delegate() {
// 当调用sayHello(anyString, anyInt)时,返回的结果就会匹配delegate方法,
// 方法名可以自定义,当入参和返回要与sayHello(anyString, anyInt)匹配上
@SuppressWarnings("unused")
String delegate(Invocation inv, String who, int gender) {
// 如果是向动物鹦鹉Polly问好,就说hello,Polly
if ("Polly".equals(who)) {
return "hello,Polly";
}
// 其它的入参,还是走原有的方法调用
return inv.proceed(who, gender);
}
};
}
};
SayHello instance = new SayHello();
Assert.isTrue(instance.sayHello("david", ISayHello.MALE).equals("hello Mr david"));
Assert.isTrue(instance.sayHello("lucy", ISayHello.FEMALE).equals("hello Mrs lucy"));
Assert.isTrue(instance.sayHello("Polly", ISayHello.FEMALE).equals("hello,Polly"));
}
}