如何使用Kafka使用者为Flink CEP编写Junit测试代码

时间:2019-01-02 07:11:59

标签: apache-kafka apache-flink flink-cep

我们有一个execute()方法,其中我们使用FlinkKafkaConsumer08作为Flink CEP源,然后有了CEP模式,警报再次出现在另一个kafka主题中。如何为此execute()方法编写一个junit测试用例?有人可以为此提供示例junit代码吗?

Pattern.<WebConnectionUseCase>begin("start")
                .where(new SimpleCondition<WebConnectionUseCase>() {
                    public boolean filter(WebConnectionUseCase event) {
                        return ((event.getValues().getPredictedAvailableMemory()
                                - event.getValues().getAvailableMemory()) >= STARTDIFF);
                    }
                }).followedBy("middle").where(new IterativeCondition<WebConnectionUseCase>() {
                    public boolean filter(WebConnectionUseCase value, Context<WebConnectionUseCase> ctx)
                            throws Exception {

                        Iterable<WebConnectionUseCase> middleStops = ctx.getEventsForPattern("middle");
                        List<Double> diffMemoryList = new ArrayList<Double>();
                        List<Double> connectionList = new ArrayList<Double>();
                        middleStops.forEach(item -> diffMemoryList.add(item.getValues().getPredictedAvailableMemory()
                                - item.getValues().getAvailableMemory()));
                        middleStops.forEach(item -> connectionList.add(item.getValues().getConnection()));
                        return checkIncreasingPattern(diffMemoryList) && checkDecreasingPattern(connectionList);
                    }

                    private boolean checkDecreasingPattern(List<Double> list) {
                        //code
                    }

                    private boolean checkIncreasingPattern(List<Double> list) {
                        // code
                    }
                }).times(PATTERNCOUNT).consecutive().next("end").where(new SimpleCondition<WebConnectionUseCase>() {
                    @Override
                    public boolean filter(WebConnectionUseCase event) {
                        return ((event.getValues().getPredictedAvailableMemory()
                                - event.getValues().getAvailableMemory()) >= ENDDIFF);
                    }
                }).within(Time.minutes(TIMEOUTDURATION));

1 个答案:

答案 0 :(得分:0)

我会将要测试的零件封装在一个对象中,该对象可以连接到特殊的源和接收器进行测试,并连接到实时数据源/接收器进行生产。

对于测试接收器,您可以使用:

public static class TestSink<OUT> implements SinkFunction<OUT> {

    // must be static
    public static final List values = new ArrayList<>();

    @Override
    public void invoke(OUT value, Context context) throws Exception {
        values.add(value);
    }
}

然后您的测试可以将sink.values与预期结果进行比较。

编写进行事件时间处理的测试(与使用处理时间的测试相比)更加容易,因为处理时间不确定结果。而且,为了获得确定性的结果,使测试以1的并行度运行更容易。

您会找到一些测试示例here