解決moco框架API在cycle方法缺失的問題

我在使用moco框架過程當中,遇到一個問題,在官方文檔中給出了cycle的方法,表示循環返回一個數組裏面的response,可是在查看API的時候並無發現這個cycle()方法,因此以爲本身寫了一個responsehandle,而且重寫了cycle()方法。java

cycle方法主要用在請求次數相關的內容,好比訂單提交、資源刪除等場景。git

package com.fun.moco.support;

import com.github.dreamhead.moco.MocoConfig;
import com.github.dreamhead.moco.ResponseHandler;
import com.github.dreamhead.moco.handler.AbstractResponseHandler;
import com.github.dreamhead.moco.internal.SessionContext;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.FluentIterable.from;
import static com.google.common.collect.ImmutableList.copyOf;

/**
 * 循環的responsehandle
 */
@SuppressWarnings("all")
public class CycleHandle extends AbstractResponseHandler {

    private final ImmutableList<ResponseHandler> handlers;

    private int index;

    private CycleHandle(final Iterable<ResponseHandler> handlers) {
        this.handlers = copyOf(handlers);
    }

    public static ResponseHandler newSeq(final Iterable<ResponseHandler> handlers) {
        checkArgument(Iterables.size(handlers) > 0, "Sequence contents should not be null");
        return new CycleHandle(handlers);
    }

    @Override
    public void writeToResponse(final SessionContext context) {
        handlers.get((index++) % handlers.size()).writeToResponse(context);
    }

    @Override
    public ResponseHandler apply(final MocoConfig config) {
        if (config.isFor(MocoConfig.RESPONSE_ID)) {
            return super.apply(config);
        }

        FluentIterable<ResponseHandler> transformedResources = from(copyOf(handlers)).transform(applyConfig(config));
        return new CycleHandle(transformedResources.toList());
    }

    private Function<ResponseHandler, ResponseHandler> applyConfig(final MocoConfig config) {
        return new Function<ResponseHandler, ResponseHandler>() {
            @Override
            public ResponseHandler apply(final ResponseHandler input) {
                return input.apply(config);
            }
        };
    }
}
使用方法以下(groovy,有興趣能夠轉成java):

/**
 * 循環返回
 * @param content
 * @param contents
 * @return
 */
    static ResponseHandler cycle(String content, String... contents) {
        CycleHandle.newSeq(FluentIterable.from(asIterable(content, contents)).transform(textToResource()))
    }

/**
 * 循環返回
 * @param handler
 * @param handlers
 * @return
 */
    static ResponseHandler cycle(final ResponseHandler handler, final ResponseHandler... handlers) {
        CycleHandle.newSeq(asIterable(handler, handlers))
    }

聯繫咱們或者加入咱們github

相關文章
相關標籤/搜索