首页 > 解决方案 > 如何模拟 GSON 自定义解串器?

问题描述

我正在尝试模拟此“活动代码反序列化器”以进行代码覆盖,但它似乎失败了。此反序列化器在其余客户端的 GSON 构建器中调用

public class ActivityCodeDeserializer implements JsonDeserializer<ActivityCode> {

    @Override
    public ActivityCode deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        return ActivityCode.toSignerActivityCode(jsonElement.getAsInt());
    }
}

这反过来调用带有代码和活动代码的枚举类

public enum ActivityCode{
    UNKNOWN(-1),
    INITIATION_SENT(101),
    RECEIVED(102),


    private static Map<Integer, ActivityCode> values = new HashMap<>();
    private int statusCode = -1;

    static {
        for (ActivityCode signerActivity : values()) {
            values.put(signerActivity.value(), signerActivity);
        }
    }

    ActivityCode(int status) {
        this.statusCode = status;
    }

    public int value() {
        return statusCode;
    }

    public static ActivityCode toSignerActivityCode(int statusCode) {
        return values.containsKey(statusCode) ? values.get(statusCode) : UNKNOWN;
    }

    @Override
    public String toString() {
        return "Activity{" +
                "statusCode=" + statusCode +
                ", name=" + name() +
                '}';
    }
}

标签: javajsonmockitogsonpowermockito

解决方案


推荐阅读