1

此代码用于为元素生成单个 Map 条目。但我想使用 generateInputMapElements 从地图中生成随机数量的条目并传递给 statusReturnedFromApplyingRule()

@Property
        //@Report(Reporting.GENERATED)
    boolean statusReturnedFromApplyingRule(@ForAll("generateRule") Rule rule,
                                           @ForAll("generateInputMapElements") Iterable<Map<String, Object>> elements) {
        RangeMatchRule rangeMatchRule = new RangeMatchRule();
        final RuleIF.Status status = rangeMatchRule.applyRule(rule, elements);
        return RuleIF.getEnums().contains(status.toString());
    }

    @Provide
Arbitrary<Iterable<Map<String, Object>>> generateInputMapElements() {
    Arbitrary<Double> metricValueArb = Arbitraries.doubles()
            .between(0, 50.0);

    Arbitrary<Map<String, Object>> inputMapArb =
            metricValueArb.map(metricsValue -> {
                Map<String, Object> inputMap = new HashMap<>();
                inputMap.put(Utils.METRIC_VALUE, metricsValue);
                return inputMap;
            });
    return inputMapArb.map(inputMap -> {
        List<Map<String, Object>> inputMapLst = new ArrayList<>();
        inputMapLst.add(inputMap);
        return inputMapLst;
    });
}

如何使用嵌套生成器编写 jqwik 生成器方法

4

1 回答 1

1

假设您想要一个包含单个条目的地图列表(可迭代),我看到两个基本选项。

选项 1 -Arbitrary.list()用于生成列表并直接在生成器代码中指定最小和最大大小:

@Provide
Arbitrary<List<Map<String, Object>>> generateInputMapElements() {
    Arbitrary<Double> metricValueArb = Arbitraries.doubles()
                                                  .between(0, 50.0);

    return metricValueArb
        .map(metricsValue -> {
            Map<String, Object> inputMap = new HashMap<>();
            inputMap.put(Utils.METRIC_VALUE, metricsValue);
            return inputMap;
        })
        .list().ofMinSize(1).ofMaxSize(10);
}

选项 2 - 仅生成单个地图并为可迭代使用标准注释:

@Property
@Report(Reporting.GENERATED)
boolean statusReturnedFromApplyingRule2(
    @ForAll("generateRule") Rule rule,
    @ForAll @Size(min = 1, max = 10) Iterable<@From("generateInputMap") Map<String, Object>> elements
) {
    ...
}

@Provide
Arbitrary<Map<String, Object>> generateInputMap() {
    Arbitrary<Double> metricValueArb = Arbitraries.doubles()
                                                  .between(0, 50.0);

    return metricValueArb
        .map(metricsValue -> {
            Map<String, Object> inputMap = new HashMap<>();
            inputMap.put(Utils.METRIC_VALUE, metricsValue);
            return inputMap;
        });
}

我个人会选择选项 2,因为它需要更少的代码。虽然是 YMMV。

于 2019-10-25T07:36:34.093 回答