问题
This code works to generate a Single Map entry for elements. But I want to generate a random number of entries from within the Map using generateInputMapElements and pass to the 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;
});
}
How to write a jqwik generator method with nested generators
回答1:
Assuming that you want a list (iterable) of maps with a single entry, I see two basic options.
Option 1 - Use Arbitrary.list()
to generate a list and specify min and max size directly in the generator code:
@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);
}
Option 2 - Generate only the individual maps and use standard annotations for the iterable:
@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;
});
}
I'd personally go with option 2 because it requires less code. YMMV though.
来源:https://stackoverflow.com/questions/58548769/jqwik-arbitrary-map-generate-a-random-number-of-entries-within-a-map