Cucumber验证运行时JSON:字符串内正则表达式失效求助
解决方案:Cucumber验证含随机数字的JSON
你之前的验证方式失败,核心原因是普通JSON字符串模板不支持正则表达式——Cucumber默认会把你的模板当成字面量字符串,和目标JSON做严格相等匹配,B[0-9]+会被当成普通文本,自然和B1234不匹配,导致验证失败。
下面提供几种可行的解决方案:
方案1:自定义步骤结合正则断言
直接在Cucumber步骤定义里解析JSON,提取目标字段后用正则做断言。以Java为例:
import io.cucumber.java.en.Then; import org.json.JSONArray; import org.json.JSONObject; import static org.junit.Assert.*; public class JsonValidationSteps { // 假设已通过前置步骤将返回的JSON存入responseJson private JSONObject responseJson; @Then("验证返回的JSON符合预期格式") public void validateJsonPattern() { JSONArray k1Array = responseJson.getJSONArray("k1"); // 验证第一个元素为"A" assertEquals("A", k1Array.getString(0)); // 验证第二个元素符合"B+数字"的格式 String secondItem = k1Array.getString(1); assertTrue(secondItem.matches("B\\d+")); } }
方案2:使用JSON Schema验证
定义一个支持正则约束的JSON Schema,再用Schema验证库结合Cucumber完成验证:
- 编写JSON Schema文件(比如存为
src/test/resources/expected-schema.json):
{ "type": "object", "properties": { "k1": { "type": "array", "items": [ {"type": "string", "const": "A"}, {"type": "string", "pattern": "^B\\d+$"} ], "minItems": 2, "maxItems": 2 } }, "required": ["k1"] }
- 在Cucumber步骤中加载Schema并验证:
import io.cucumber.java.en.Then; import org.everit.json.schema.Schema; import org.everit.json.schema.loader.SchemaLoader; import org.json.JSONObject; import org.json.JSONTokener; import static org.junit.Assert.fail; public class JsonSchemaSteps { private JSONObject responseJson; @Then("验证返回的JSON符合Schema约束") public void validateAgainstSchema() { try { JSONObject schemaJson = new JSONObject(new JSONTokener( getClass().getResourceAsStream("/expected-schema.json") )); Schema schema = SchemaLoader.load(schemaJson); schema.validate(responseJson); } catch (Exception e) { fail("JSON不符合预期Schema:" + e.getMessage()); } } }
方案3:Groovy环境下用GPath简化验证
如果你的Cucumber用Groovy编写,可直接用JsonSlurper结合正则匹配:
Then(/^验证返回JSON格式正确$/) { -> def json = new JsonSlurper().parseText(responseBody) assert json.k1[0] == "A" assert json.k1[1] ==~ /B\d+/ }
内容的提问来源于stack exchange,提问作者S Singh
相关产品推荐
相关产品推荐

