org.test4j.mock.faking.fluent.MethodBehaviors Maven / Gradle / Ivy
package org.test4j.mock.faking.fluent;
import lombok.Getter;
import org.test4j.mock.faking.meta.MethodId;
import org.test4j.mock.faking.util.TypeUtility;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* 类declaredToFake所有mock行为定义
*
* key: method description, 比如: sayHello(Ljava/lang/String;)
* value: invoke times->MockBehavior
*/
@SuppressWarnings("rawtypes")
public class MethodBehaviors extends HashMap> {
private final String declaredToFake;
/**
* 需要mock的方法列表
*/
@Getter
private final Set methodIds = new HashSet<>();
MethodBehaviors(Class declaredToFake) {
this.declaredToFake = TypeUtility.classPath(declaredToFake);
}
/**
* 增加方法的mock定义
*
* @param realClass 实际定义类
* @param name 方法名称, 比如: sayHello
* @param desc 方法 "(入参列表)返回值" 签名, 比如: (Ljava/lang/String;)Ljava/lang/String;
* @param index mock实际调用的第index次行为, 从1开始计数
* @param behavior 行为定义
*/
public MethodId addMockBehavior(String realClass, String name, String desc, int index, MockBehavior behavior) {
MethodId meta = this.initMeta(realClass, name, desc);
this.get(meta.methodDesc).put(index, behavior);
return meta;
}
private MethodId initMeta(String realClass, String name, String desc) {
MethodId meta = new MethodId(this.declaredToFake, realClass, name, desc);
this.methodIds.add(meta);
if (!this.containsKey(meta.methodDesc)) {
this.put(meta.methodDesc, new HashMap<>());
}
return meta;
}
@Override
public void clear() {
super.clear();
this.methodIds.clear();
}
}