Pact匹配规则中min与max无法同时生效,如何校验数组元素数量范围?
How to Enforce Both Min and Max Array Length in Pact's Matching Rules
Great question—this is a common gotcha with Pact's matching rules, especially when you're first figuring out how to combine length constraints for arrays. Let's break down why your previous attempts didn't work and how to fix it.
Why Your Previous Approaches Failed
- Combining
minandmaxwithout specifying the match type: When you wrote"$.body": { "min": 1, "max": 2 }, Pact didn't recognize you were targeting an array specifically. Without amatchproperty defining the field type (like"array"or"arrayLike"), Pact only prioritizes one constraint (usuallyminhere) and ignores the other. - Duplicate keys in the matching rules object: JSON doesn't allow duplicate top-level keys in an object. When you added two separate
"$.body"entries, the second one overwrote the first entirely—so only themaxrule took effect.
The Correct Solution
To enforce both a minimum and maximum array length, you need to:
- Explicitly declare the target field is an array using the
matchproperty - Include both
minandmaxconstraints in the same rule object
Here's a working example for an array at $.body:
"matchingRules": { "$.body": { "match": "array", "min": 1, "max": 2 } }
If your array has structured elements you also want to validate (not just length), use "arrayLike" instead and add matchers for the elements:
"matchingRules": { "$.body": { "match": "arrayLike", "min": 1, "max": 2, "matchers": [ { "$": { "match": "type" // Validates each element is the correct type (e.g., object) } } ] } }
How This Works
- The
"match": "array"(or"arrayLike") tells Pact that$.bodymust be an array. - The
minandmaxproperties work together to enforce the array has between 1 and 2 elements, inclusive. - Pact will now fail verification if the array has fewer than 1 element (violating
min) or more than 2 elements (violatingmax).
内容的提问来源于stack exchange,提问作者Oliver Sanftleben
相关产品推荐
相关产品推荐

