Best Citrus code snippet using com.consol.citrus.validation.json.JsonTextMessageValidator.JsonSchemaValidation
Source:JsonTextMessageValidatorTest.java
...20import com.consol.citrus.message.DefaultMessage;21import com.consol.citrus.message.Message;22import com.consol.citrus.testng.AbstractTestNGUnitTest;23import com.consol.citrus.validation.json.report.GraciousProcessingReport;24import com.consol.citrus.validation.json.schema.JsonSchemaValidation;25import net.minidev.json.parser.ParseException;26import org.springframework.beans.factory.annotation.Autowired;27import org.springframework.beans.factory.annotation.Qualifier;28import org.testng.Assert;29import org.testng.annotations.Test;30import java.util.Collections;31import static org.mockito.ArgumentMatchers.any;32import static org.mockito.ArgumentMatchers.anyList;33import static org.mockito.ArgumentMatchers.eq;34import static org.mockito.Mockito.mock;35import static org.mockito.Mockito.verify;36import static org.mockito.Mockito.when;37/**38 * @author Christoph Deppisch39 */40public class JsonTextMessageValidatorTest extends AbstractTestNGUnitTest {41 @Autowired42 @Qualifier("defaultJsonMessageValidator")43 private JsonTextMessageValidator validator;44 @Test45 public void testJsonValidation() {46 JsonTextMessageValidator validator = new JsonTextMessageValidator();47 Message receivedMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"id\":\"x123456789x\"}");48 Message controlMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"id\":\"x123456789x\"}");49 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();50 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);51 }52 @Test53 public void testSloppyJsonValidation() {54 JsonTextMessageValidator validator = new JsonTextMessageValidator().strict(false);55 Message receivedMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"id\":\"x123456789x\"}");56 Message controlMessage = new DefaultMessage("{\"id\":\"x123456789x\"}");57 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();58 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);59 }60 @Test61 public void testJsonValidationNestedObjects() {62 JsonTextMessageValidator validator = new JsonTextMessageValidator();63 64 Message receivedMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"person\":{\"name\":\"John\",\"surname\":\"Doe\"}, \"index\":5, \"id\":\"x123456789x\"}");65 Message controlMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"person\":{\"name\":\"John\",\"surname\":\"Doe\"}, \"index\":5, \"id\":\"x123456789x\"}");66 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();67 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);68 }69 70 @Test71 public void testJsonValidationWithArrays() {72 JsonTextMessageValidator validator = new JsonTextMessageValidator();73 Message receivedMessage = new DefaultMessage("[" +74 "{\"text\":\"Hello World!\", \"index\":1}, " +75 "{\"text\":\"Hallo Welt!\", \"index\":2}, " +76 "{\"text\":\"Hola del mundo!\", \"index\":3}]");77 Message controlMessage = new DefaultMessage("[" +78 "{\"text\":\"Hello World!\", \"index\":1}, " +79 "{\"text\":\"Hallo Welt!\", \"index\":2}, " +80 "{\"text\":\"Hola del mundo!\", \"index\":3}]");81 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();82 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);83 }84 @Test85 public void testSloppyJsonValidationWithArrays() {86 JsonTextMessageValidator validator = new JsonTextMessageValidator();87 validator.setStrict(false);88 Message receivedMessage = new DefaultMessage("[" +89 "{\"text\":\"Hello World!\", \"index\":1}, " +90 "{\"text\":\"Hallo Welt!\", \"index\":2}, " +91 "{\"text\":\"Hola del mundo!\", \"index\":3}]");92 Message controlMessage = new DefaultMessage("[{\"text\":\"Hello World!\", \"index\":1}] ");93 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();94 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);95 }96 @Test97 public void testJsonValidationWithNestedArrays() {98 JsonTextMessageValidator validator = new JsonTextMessageValidator();99 100 Message receivedMessage = new DefaultMessage("{\"greetings\":[" +101 "{\"text\":\"Hello World!\", \"index\":1}, " +102 "{\"text\":\"Hallo Welt!\", \"index\":2}, " +103 "{\"text\":\"Hola del mundo!\", \"index\":3}], \"id\":\"x123456789x\"}");104 Message controlMessage = new DefaultMessage("{\"greetings\":[" +105 "{\"text\":\"Hello World!\", \"index\":1}, " +106 "{\"text\":\"Hallo Welt!\", \"index\":2}, " +107 "{\"text\":\"Hola del mundo!\", \"index\":3}], \"id\":\"x123456789x\"}");108 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();109 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);110 }111 112 @Test113 public void testJsonValidationVariableSupport() {114 JsonTextMessageValidator validator = new JsonTextMessageValidator();115 116 Message receivedMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"id\":\"x123456789x\"}");117 Message controlMessage = new DefaultMessage("{\"text\":\"Hello ${world}!\", \"index\":${index}, \"id\":\"${id}\"}");118 119 context.setVariable("world", "World");120 context.setVariable("index", "5");121 context.setVariable("id", "x123456789x");122 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();123 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);124 }125 126 @Test127 public void testJsonValidationWrongNumberOfEntries() {128 JsonTextMessageValidator validator = new JsonTextMessageValidator();129 130 Message receivedMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"id\":\"x123456789x\"}");131 Message controlMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"id\":\"x123456789x\", \"missing\":\"this is missing\"}");132 133 try {134 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();135 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);136 } catch (ValidationException e) {137 Assert.assertTrue(e.getMessage().contains("expected '4'"));138 Assert.assertTrue(e.getMessage().contains("but was '3'"));139 140 return;141 }142 143 Assert.fail("Missing validation exception due to wrong number of JSON entries");144 }145 146 @Test147 public void testJsonValidationWrongValue() {148 JsonTextMessageValidator validator = new JsonTextMessageValidator();149 150 Message receivedMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"id\":\"wrong\"}");151 Message controlMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"id\":\"x123456789x\"}");152 153 try {154 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();155 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);156 } catch (ValidationException e) {157 Assert.assertTrue(e.getMessage().contains("expected 'x123456789x'"));158 Assert.assertTrue(e.getMessage().contains("but was 'wrong'"));159 160 return;161 }162 163 Assert.fail("Missing validation exception due to wrong value");164 }165 166 @Test167 public void testJsonValidationWrongValueInNestedObjects() {168 JsonTextMessageValidator validator = new JsonTextMessageValidator();169 170 Message receivedMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"person\":{\"name\":\"John\",\"surname\":\"wrong\"}, \"index\":5, \"id\":\"x123456789x\"}");171 Message controlMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"person\":{\"name\":\"John\",\"surname\":\"Doe\"}, \"index\":5, \"id\":\"x123456789x\"}");172 173 try {174 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();175 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);176 } catch (ValidationException e) {177 Assert.assertTrue(e.getMessage().contains("expected 'Doe'"));178 Assert.assertTrue(e.getMessage().contains("but was 'wrong'"));179 180 return;181 }182 183 Assert.fail("Missing validation exception due to wrong value");184 }185 186 @Test187 public void testJsonValidationWrongValueInArrays() {188 JsonTextMessageValidator validator = new JsonTextMessageValidator();189 190 Message receivedMessage = new DefaultMessage("{\"greetings\":[" +191 "{\"text\":\"Hello World!\", \"index\":1}, " +192 "{\"text\":\"Hallo Welt!\", \"index\":0}, " +193 "{\"text\":\"Hola del mundo!\", \"index\":3}], \"id\":\"x123456789x\"}");194 Message controlMessage = new DefaultMessage("{\"greetings\":[" +195 "{\"text\":\"Hello World!\", \"index\":1}, " +196 "{\"text\":\"Hallo Welt!\", \"index\":2}, " +197 "{\"text\":\"Hola del mundo!\", \"index\":3}], \"id\":\"x123456789x\"}");198 199 try {200 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();201 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);202 } catch (ValidationException e) {203 Assert.assertTrue(e.getMessage().contains("expected '2'"));204 Assert.assertTrue(e.getMessage().contains("but was '0'"));205 206 return;207 }208 209 Assert.fail("Missing validation exception due to wrong value");210 }211 212 @Test213 public void testJsonValidationWrongArraySize() {214 JsonTextMessageValidator validator = new JsonTextMessageValidator();215 216 Message receivedMessage = new DefaultMessage("{\"greetings\":[" +217 "{\"text\":\"Hello World!\", \"index\":1}, " +218 "{\"text\":\"Hallo Welt!\", \"index\":2}], \"id\":\"x123456789x\"}");219 Message controlMessage = new DefaultMessage("{\"greetings\":[" +220 "{\"text\":\"Hello World!\", \"index\":1}, " +221 "{\"text\":\"Hallo Welt!\", \"index\":2}, " +222 "{\"text\":\"Hola del mundo!\", \"index\":3}], \"id\":\"x123456789x\"}");223 224 try {225 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();226 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);227 } catch (ValidationException e) {228 Assert.assertTrue(e.getMessage().contains("expected '3'"));229 Assert.assertTrue(e.getMessage().contains("but was '2'"));230 231 return;232 }233 234 Assert.fail("Missing validation exception due to wrong array size");235 }236 237 @Test238 public void testJsonValidationArrayTypeMismatch() {239 JsonTextMessageValidator validator = new JsonTextMessageValidator();240 241 Message receivedMessage = new DefaultMessage("{\"greetings\":{\"text\":\"Hello World!\", \"index\":1}, \"id\":\"x123456789x\"}");242 Message controlMessage = new DefaultMessage("{\"greetings\":[" +243 "{\"text\":\"Hello World!\", \"index\":1}, " +244 "{\"text\":\"Hallo Welt!\", \"index\":2}, " +245 "{\"text\":\"Hola del mundo!\", \"index\":3}], \"id\":\"x123456789x\"}");246 247 try {248 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();249 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);250 } catch (ValidationException e) {251 Assert.assertTrue(e.getMessage().contains("expected 'JSONArray'"));252 Assert.assertTrue(e.getMessage().contains("but was 'JSONObject'"));253 254 return;255 }256 257 Assert.fail("Missing validation exception due to type mismatch");258 }259 260 @Test261 public void testJsonValidationObjectTypeMismatch() {262 JsonTextMessageValidator validator = new JsonTextMessageValidator();263 264 Message receivedMessage = new DefaultMessage("{\"greetings\":[" +265 "{\"text\":\"Hello World!\", \"index\":1}, " +266 "{\"text\":\"Hallo Welt!\", \"index\":2}, " +267 "{\"text\":\"Hola del mundo!\", \"index\":3}], \"id\":\"x123456789x\"}");268 Message controlMessage = new DefaultMessage("{\"greetings\":{\"text\":\"Hello World!\", \"index\":1}, \"id\":\"x123456789x\"}");269 270 try {271 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();272 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);273 } catch (ValidationException e) {274 Assert.assertTrue(e.getMessage().contains("expected 'JSONObject'"));275 Assert.assertTrue(e.getMessage().contains("but was 'JSONArray'"));276 277 return;278 }279 280 Assert.fail("Missing validation exception due to type mismatch");281 }282 283 @Test284 public void testJsonValidationIgnorePlaceholder() {285 JsonTextMessageValidator validator = new JsonTextMessageValidator();286 287 Message receivedMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"object\":{\"id\":\"x123456789x\"}, \"greetings\":[" +288 "{\"text\":\"Hello World!\", \"index\":1}, " +289 "{\"text\":\"Hallo Welt!\", \"index\":2}, " +290 "{\"text\":\"Hola del mundo!\", \"index\":3}],}");291 Message controlMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":\"@ignore@\", \"object\":{\"id\":\"@ignore@\"}, \"greetings\":\"@ignore@\"}");292 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();293 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);294 }295 @Test296 public void testJsonValidationIgnoreEntries() {297 JsonTextMessageValidator validator = new JsonTextMessageValidator();298 Message receivedMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"object\":{\"id\":\"x123456789x\"}, \"greetings\":[" +299 "{\"text\":\"Hello World!\", \"index\":1}, " +300 "{\"text\":\"Hallo Welt!\", \"index\":2}, " +301 "{\"text\":\"Hola del mundo!\", \"index\":3}],}");302 Message controlMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":\"?\", \"object\":{\"id\":\"?\"}, \"greetings\":\"?\"}");303 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();304 validationContext.getIgnoreExpressions().add("$..index");305 validationContext.getIgnoreExpressions().add("$.object.id");306 validationContext.getIgnoreExpressions().add("$.greetings");307 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);308 }309 310 @Test311 public void testJsonValidationInvalidJsonText() {312 JsonTextMessageValidator validator = new JsonTextMessageValidator();313 314 Message receivedMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"id\":\"wrong\"}");315 Message controlMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":invalid, \"id\":\"x123456789x\"}");316 317 try {318 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();319 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);320 } catch (CitrusRuntimeException e) {321 Assert.assertTrue(e.getCause() instanceof ParseException);322 323 return;324 }325 326 Assert.fail("Missing validation exception due to wrong value");327 }328 329 @Test330 public void testJsonNullValueValidation() {331 JsonTextMessageValidator validator = new JsonTextMessageValidator();332 333 Message receivedMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"id\":null}");334 Message controlMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"id\":null}");335 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();336 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);337 }338 339 @Test340 public void testJsonEmptyMessageValidation() {341 JsonTextMessageValidator validator = new JsonTextMessageValidator();342 343 Message receivedMessage = new DefaultMessage("");344 Message controlMessage = new DefaultMessage("");345 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();346 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);347 }348 349 @Test350 public void testJsonEmptyMessageValidationError() {351 JsonTextMessageValidator validator = new JsonTextMessageValidator();352 353 Message receivedMessage = new DefaultMessage("");354 Message controlMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"id\":\"x123456789x\"}");355 356 try {357 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();358 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);359 Assert.fail("Missing validation exception due to validation error");360 } catch (ValidationException e) {361 Assert.assertTrue(e.getMessage().contains("expected message contents, but received empty message"));362 }363 364 receivedMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"id\":\"x123456789x\"}");365 controlMessage = new DefaultMessage("");366 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();367 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);368 }369 370 @Test371 public void testJsonNullValueMismatch() {372 JsonTextMessageValidator validator = new JsonTextMessageValidator();373 374 Message receivedMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"id\":\"x123456789x\"}");375 Message controlMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"id\":null}");376 377 try {378 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();379 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);380 Assert.fail("Missing validation exception due to wrong value");381 } catch (ValidationException e) {382 Assert.assertTrue(e.getMessage().contains("expected 'null' but was 'x123456789x'"));383 }384 385 receivedMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"id\":null}");386 controlMessage = new DefaultMessage("{\"text\":\"Hello World!\", \"index\":5, \"id\":\"x123456789x\"}");387 388 try {389 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();390 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);391 Assert.fail("Missing validation exception due to wrong value");392 } catch (ValidationException e) {393 Assert.assertTrue(e.getMessage().contains("expected 'x123456789x' but was 'null'"));394 }395 }396 @Test397 public void testUseSchemaRepositoryValidatorIfSchemaValidationIsEnabled() {398 //GIVEN399 JsonMessageValidationContext validationContext = new JsonMessageValidationContext();400 validationContext.setSchemaValidation(true);401 JsonSchemaValidation jsonSchemaValidation = mock(JsonSchemaValidation.class);402 when(jsonSchemaValidation.validate(any(), anyList(), any(), any())).thenReturn(new GraciousProcessingReport((true)));403 validator.setJsonSchemaValidation(jsonSchemaValidation);404 JsonSchemaRepository jsonSchemaRepository = mock(JsonSchemaRepository.class);405 validator.setSchemaRepositories(Collections.singletonList(jsonSchemaRepository));406 Message receivedMessage = new DefaultMessage("{\"id\":42}");407 Message controlMessage = new DefaultMessage("{\"id\":42}");408 //WHEN409 validator.validateMessage(receivedMessage, controlMessage, context, validationContext);410 //THEN411 verify(jsonSchemaValidation).validate(eq(receivedMessage), anyList(), eq(validationContext), eq(applicationContext));412 }413}...
Source:JsonTextMessageValidator.java
...28import com.consol.citrus.message.MessageType;29import com.consol.citrus.util.MessageUtils;30import com.consol.citrus.validation.AbstractMessageValidator;31import com.consol.citrus.validation.ValidationUtils;32import com.consol.citrus.validation.json.schema.JsonSchemaValidation;33import com.consol.citrus.validation.matcher.ValidationMatcherUtils;34import com.github.fge.jsonschema.core.report.ProcessingReport;35import com.jayway.jsonpath.JsonPath;36import com.jayway.jsonpath.ReadContext;37import net.minidev.json.JSONArray;38import net.minidev.json.JSONObject;39import net.minidev.json.parser.JSONParser;40import net.minidev.json.parser.ParseException;41import org.springframework.util.Assert;42import org.springframework.util.StringUtils;43/**44 * This message validator implementation is able to validate two JSON text objects. The order of JSON entries can differ45 * as specified in JSON protocol. Tester defines an expected control JSON text with optional ignored entries.46 *47 * JSONArray as well as nested JSONObjects are supported, too.48 *49 * Validator offers two different modes to operate. By default strict mode is set and the validator will also check the exact amount of50 * control object fields to match. No additional fields in received JSON data structure will be accepted. In soft mode validator51 * allows additional fields in received JSON data structure so the control JSON object can be a partial subset.52 *53 * @author Christoph Deppisch54 */55public class JsonTextMessageValidator extends AbstractMessageValidator<JsonMessageValidationContext> {56 /** Should also check exact amount of object fields */57 private boolean strict = JsonSettings.isStrict();58 /** Permissive mode to use on the Json parser */59 private int permissiveMode = JsonSettings.getPermissiveMoe();60 /** Schema validator */61 private JsonSchemaValidation jsonSchemaValidation = new JsonSchemaValidation();62 @Override63 @SuppressWarnings("unchecked")64 public void validateMessage(Message receivedMessage, Message controlMessage,65 TestContext context, JsonMessageValidationContext validationContext) {66 if (controlMessage == null || controlMessage.getPayload() == null) {67 log.debug("Skip message payload validation as no control message was defined");68 return;69 }70 log.debug("Start JSON message validation ...");71 if (validationContext.isSchemaValidationEnabled()) {72 jsonSchemaValidation.validate(receivedMessage, context, validationContext);73 }74 if (log.isDebugEnabled()) {75 log.debug("Received message:\n" + receivedMessage.print(context));76 log.debug("Control message:\n" + controlMessage.print(context));77 }78 String receivedJsonText = receivedMessage.getPayload(String.class);79 String controlJsonText = context.replaceDynamicContentInString(controlMessage.getPayload(String.class));80 try {81 if (!StringUtils.hasText(controlJsonText)) {82 log.debug("Skip message payload validation as no control message was defined");83 return;84 } else {85 Assert.isTrue(StringUtils.hasText(receivedJsonText), "Validation failed - " +86 "expected message contents, but received empty message!");87 }88 JSONParser parser = new JSONParser(permissiveMode);89 Object receivedJson = parser.parse(receivedJsonText);90 ReadContext readContext = JsonPath.parse(receivedJson);91 Object controlJson = parser.parse(controlJsonText);92 if (receivedJson instanceof JSONObject) {93 validateJson("$.", (JSONObject) receivedJson, (JSONObject) controlJson, validationContext, context, readContext);94 } else if (receivedJson instanceof JSONArray) {95 JSONObject tempReceived = new JSONObject();96 tempReceived.put("array", receivedJson);97 JSONObject tempControl = new JSONObject();98 tempControl.put("array", controlJson);99 validateJson("$.", tempReceived, tempControl, validationContext, context, readContext);100 } else {101 throw new CitrusRuntimeException("Unsupported json type " + receivedJson.getClass());102 }103 } catch (IllegalArgumentException e) {104 throw new ValidationException(String.format("Failed to validate JSON text:%n%s", receivedJsonText), e);105 } catch (ParseException e) {106 throw new CitrusRuntimeException("Failed to parse JSON text", e);107 }108 log.info("JSON message validation successful: All values OK");109 }110 /**111 * Find json schema repositories in test context.112 * @param context113 * @return114 */115 private List<JsonSchemaRepository> findSchemaRepositories(TestContext context) {116 return new ArrayList<>(context.getReferenceResolver().resolveAll(JsonSchemaRepository.class).values());117 }118 /**119 * Validates JSON text with comparison to expected control JSON object.120 * JSON entries can be ignored with ignore placeholder.121 *122 * @param elementName the current element name that is under verification in this method123 * @param receivedJson the received JSON text object.124 * @param controlJson the expected control JSON text.125 * @param validationContext the JSON message validation context.126 * @param context the current test context.127 * @param readContext the JSONPath read context.128 */129 @SuppressWarnings("rawtypes")130 public void validateJson(String elementName, JSONObject receivedJson, JSONObject controlJson, JsonMessageValidationContext validationContext, TestContext context, ReadContext readContext) {131 if (strict) {132 Assert.isTrue(controlJson.size() == receivedJson.size(),133 ValidationUtils.buildValueMismatchErrorMessage("Number of JSON entries not equal for element: '" + elementName + "'", controlJson.size(), receivedJson.size()));134 }135 for (Map.Entry<String, Object> controlJsonEntry : controlJson.entrySet()) {136 String controlKey = controlJsonEntry.getKey();137 Assert.isTrue(receivedJson.containsKey(controlKey),138 "Missing JSON entry: + '" + controlKey + "'");139 Object controlValue = controlJsonEntry.getValue();140 Object receivedValue = receivedJson.get(controlKey);141 // check if entry is ignored by placeholder142 if (isIgnored(controlKey, controlValue, receivedValue, validationContext.getIgnoreExpressions(), readContext)) {143 continue;144 }145 if (controlValue == null) {146 Assert.isTrue(receivedValue == null,147 ValidationUtils.buildValueMismatchErrorMessage("Values not equal for entry: '" + controlKey + "'",148 null, receivedValue));149 } else if (receivedValue != null) {150 if (ValidationMatcherUtils.isValidationMatcherExpression(controlValue.toString())) {151 ValidationMatcherUtils.resolveValidationMatcher(controlKey,152 receivedValue.toString(),153 controlValue.toString(), context);154 } else if (controlValue instanceof JSONObject) {155 Assert.isTrue(receivedValue instanceof JSONObject,156 ValidationUtils.buildValueMismatchErrorMessage("Type mismatch for JSON entry '" + controlKey + "'",157 JSONObject.class.getSimpleName(), receivedValue.getClass().getSimpleName()));158 validateJson(controlKey, (JSONObject) receivedValue,159 (JSONObject) controlValue, validationContext, context, readContext);160 } else if (controlValue instanceof JSONArray) {161 Assert.isTrue(receivedValue instanceof JSONArray,162 ValidationUtils.buildValueMismatchErrorMessage("Type mismatch for JSON entry '" + controlKey + "'",163 JSONArray.class.getSimpleName(), receivedValue.getClass().getSimpleName()));164 JSONArray jsonArrayControl = (JSONArray) controlValue;165 JSONArray jsonArrayReceived = (JSONArray) receivedValue;166 if (log.isDebugEnabled()) {167 log.debug("Validating JSONArray containing " + jsonArrayControl.size() + " entries");168 }169 if (strict) {170 Assert.isTrue(jsonArrayControl.size() == jsonArrayReceived.size(),171 ValidationUtils.buildValueMismatchErrorMessage("JSONArray size mismatch for JSON entry '" + controlKey + "'",172 jsonArrayControl.size(), jsonArrayReceived.size()));173 }174 for (int i = 0; i < jsonArrayControl.size(); i++) {175 if (jsonArrayControl.get(i).getClass().isAssignableFrom(JSONObject.class)) {176 Assert.isTrue(jsonArrayReceived.get(i).getClass().isAssignableFrom(JSONObject.class),177 ValidationUtils.buildValueMismatchErrorMessage("Value types not equal for entry: '" + jsonArrayControl.get(i) + "'",178 JSONObject.class.getName(), jsonArrayReceived.get(i).getClass().getName()));179 validateJson(controlKey, (JSONObject) jsonArrayReceived.get(i),180 (JSONObject) jsonArrayControl.get(i), validationContext, context, readContext);181 } else {182 Assert.isTrue(jsonArrayControl.get(i).equals(jsonArrayReceived.get(i)),183 ValidationUtils.buildValueMismatchErrorMessage("Values not equal for entry: '" + jsonArrayControl.get(i) + "'",184 jsonArrayControl.get(i), jsonArrayReceived.get(i)));185 }186 }187 } else {188 Assert.isTrue(controlValue.equals(receivedValue),189 ValidationUtils.buildValueMismatchErrorMessage("Values not equal for entry: '" + controlKey + "'",190 controlValue, receivedValue));191 }192 } else if (ValidationMatcherUtils.isValidationMatcherExpression(controlValue.toString())) {193 ValidationMatcherUtils.resolveValidationMatcher(controlKey,194 null,195 controlValue.toString(), context);196 } else {197 Assert.isTrue(!StringUtils.hasText(controlValue.toString()),198 ValidationUtils.buildValueMismatchErrorMessage(199 "Values not equal for entry '" + controlKey + "'", controlValue.toString(), null));200 }201 if (log.isDebugEnabled()) {202 log.debug("Validation successful for JSON entry '" + controlKey + "' (" + controlValue + ")");203 }204 }205 }206 /**207 * Checks if given element node is either on ignore list or208 * contains @ignore@ tag inside control message209 * @param controlKey210 * @param controlValue211 * @param receivedJson212 * @param ignoreExpressions213 * @param readContext214 * @return215 */216 public boolean isIgnored(String controlKey, Object controlValue, Object receivedJson, Set<String> ignoreExpressions, ReadContext readContext) {217 if (controlValue != null && controlValue.toString().trim().equals(CitrusSettings.IGNORE_PLACEHOLDER)) {218 if (log.isDebugEnabled()) {219 log.debug("JSON entry: '" + controlKey + "' is ignored by placeholder '" +220 CitrusSettings.IGNORE_PLACEHOLDER + "'");221 }222 return true;223 }224 for (String jsonPathExpression : ignoreExpressions) {225 Object foundEntry = readContext.read(jsonPathExpression);226 if (foundEntry instanceof JSONArray && ((JSONArray) foundEntry).contains(receivedJson)) {227 if (log.isDebugEnabled()) {228 log.debug("JSON entry: '" + controlKey + "' is ignored - skip value validation");229 }230 return true;231 }232 if (foundEntry != null && foundEntry.equals(receivedJson)) {233 if (log.isDebugEnabled()) {234 log.debug("JSON entry: '" + controlKey + "' is ignored - skip value validation");235 }236 return true;237 }238 }239 return false;240 }241 @Override242 protected Class<JsonMessageValidationContext> getRequiredValidationContextType() {243 return JsonMessageValidationContext.class;244 }245 @Override246 public boolean supportsMessageType(String messageType, Message message) {247 return messageType.equalsIgnoreCase(MessageType.JSON.name()) && MessageUtils.hasJsonPayload(message);248 }249 /**250 * Set the validator strict mode.251 * @param strict252 */253 public void setStrict(boolean strict) {254 this.strict = strict;255 }256 /**257 * Set the validator strict mode.258 * @param strict259 * @return this object for chaining260 */261 public JsonTextMessageValidator strict(boolean strict) {262 setStrict(strict);263 return this;264 }265 /**266 * Sets the json schema validation.267 * @param jsonSchemaValidation268 */269 void setJsonSchemaValidation(JsonSchemaValidation jsonSchemaValidation) {270 this.jsonSchemaValidation = jsonSchemaValidation;271 }272 /**273 * Sets the json schema validation.274 * @param jsonSchemaValidation275 * @return this object for chaining276 */277 public JsonTextMessageValidator jsonSchemaValidation(JsonSchemaValidation jsonSchemaValidation) {278 setJsonSchemaValidation(jsonSchemaValidation);279 return this;280 }281 /**282 * Sets the permissive mode.283 * @param permissiveMode284 */285 public void setPermissiveMode(int permissiveMode) {286 this.permissiveMode = permissiveMode;287 }288 /**289 * Sets the permissive mode290 * @param permissiveMode291 * @return this object for chaining292 */...
JsonSchemaValidation
Using AI Code Generation
1package com.consol.citrus.validation.json;2import com.consol.citrus.context.TestContext;3import com.consol.citrus.exceptions.ValidationException;4import com.consol.citrus.message.Message;5import com.consol.citrus.validation.DefaultMessageValidator;6import com.consol.citrus.validation.MessageValidator;7import com.consol.citrus.validation.context.ValidationContext;8import com.consol.citrus.validation.interceptor.ValidationInterceptor;9import com.consol.citrus.validation.matcher.ValidationMatcherUtils;10import com.consol.citrus.validation.json.JsonMessageValidationContext;11import com.consol.citrus.validation.json.JsonPathMessageValidationContext;12import com.consol.citrus.validation.json.JsonSchemaMessageValidationContext;13import com.consol.citrus.validation.json.JsonTextMessageValidator;14import com.consol.citrus.validation.xml.XmlMessageValidationContext;15import com.consol.citrus.validation.xml.XmlSchemaMessageValidationContext;16import com.consol.citrus.validation.xml.XmlTextMessageValidator;17import org.slf4j.Logger;18import org.slf4j.LoggerFactory;19import org.springframework.util.StringUtils;20import javax.xml.transform.Source;21import javax.xml.transform.stream.StreamSource;22import java.io.ByteArrayInputStream;23import java.util.*;24public class JsonTextMessageValidator extends DefaultMessageValidator implements MessageValidator<JsonMessageValidationContext> {25 private static Logger log = LoggerFactory.getLogger(JsonTextMessageValidator.class);26 private final Map<String, JsonMessageValidationContext> validationContexts = new HashMap<>();27 private JsonMessageValidationContext defaultValidationContext;28 private JsonMessageValidationContext.Builder validationContextBuilder;29 private Map<String, String> schemaRepository = new HashMap<>();30 private Map<String, String> schemaRepositoryLocations = new HashMap<>();31 public JsonTextMessageValidator() {32 super("json");33 validationContextBuilder = new JsonMessageValidationContext.Builder();34 }35 public void validateMessage(Message receivedMessage, Message controlMessage, TestContext context, ValidationContext validationContext) {36 if (validationContext instanceof JsonSchemaMessageValidationContext) {37 validateMessage(receivedMessage, controlMessage, context, (JsonSchemaMessageValidationContext) validationContext);38 } else if (validationContext instanceof JsonPathMessageValidationContext)
JsonSchemaValidation
Using AI Code Generation
1import com.consol.citrus.dsl.runner.TestRunner;2import com.consol.citrus.dsl.testng.TestNGCitrusTest;3import com.consol.citrus.message.MessageType;4import org.springframework.core.io.ClassPathResource;5import org.testng.annotations.Test;6public class JsonSchemaValidationTest extends TestNGCitrusTest {7public void jsonSchemaValidationTest() {8TestRunner runner = new TestRunner(this, context);9runner.http(builder -> builder.client("httpClient")10.server("httpServer")11.send()12.post()13.messageType(MessageType.JSON)14.payload(new ClassPathResource("request.json")));15runner.http(builder -> builder.client("httpClient")16.server("httpServer")17.receive()18.response(HttpStatus.OK)19.messageType(MessageType.JSON)20.payload(new ClassPathResource("response.json")));21runner.validate(builder -> builder.json()22.schemaValidation(true)23.schema(new ClassPathResource("schema.json"))24.messageType(MessageType.JSON)25.payload(new ClassPathResource("response.json")));26}27}28import com.consol.citrus.dsl.runner.TestRunner;29import com.consol.citrus.dsl.testng.TestNGCitrusTest;30import com.consol.citrus.message.MessageType;31import org.springframework.core.io.ClassPathResource;32import org.testng.annotations.Test;33public class JsonSchemaValidationTest extends TestNGCitrusTest {34public void jsonSchemaValidationTest() {35TestRunner runner = new TestRunner(this, context);36runner.http(builder -> builder.client("httpClient")37.server("httpServer")38.send()39.post()40.messageType(MessageType.JSON)41.payload(new ClassPathResource("request.json")));42runner.http(builder -> builder.client("httpClient")43.server("httpServer")44.receive()45.response(HttpStatus.OK)46.messageType(MessageType.JSON)47.payload(new ClassPathResource("response.json")));48runner.validate(builder -> builder.json()49.schemaValidation(true)50.schema(new ClassPathResource("schema.json"))51.messageType(MessageType.JSON)52.payload(new ClassPathResource("response.json")));53}54}55import com.consol.citrus.dsl.runner.TestRunner;56import com.consol.citrus.dsl.testng.TestNGCitrusTest;57import com.consol.citrus.message.MessageType;58import org.springframework.core.io.ClassPathResource;59import org.testng.annotations.Test;
JsonSchemaValidation
Using AI Code Generation
1package com.consol.citrus.validation.json;2import java.io.IOException;3import org.testng.annotations.Test;4import com.consol.citrus.dsl.testng.TestNGCitrusTestRunner;5public class JsonSchemaValidation extends TestNGCitrusTestRunner{6 public void JsonSchemaValidation() throws IOException {7 http().client("httpClient")8 .send()9 http().client("httpClient")10 .receive()11 .response(HttpStatus.OK)12 .payload("{\"name\":\"Raj\",\"salary\":10000}");13 echo("Validating the response payload");14 validate().json().schema("/home/raj/Downloads/schema.json");15 }16}17package com.consol.citrus.validation.json;18import java.io.IOException;19import org.testng.annotations.Test;20import com.consol.citrus.dsl.testng.TestNGCitrusTestRunner;21public class JsonSchemaValidation extends TestNGCitrusTestRunner{22 public void JsonSchemaValidation() throws IOException {23 http().client("httpClient")24 .send()25 http().client("httpClient")26 .receive()27 .response(HttpStatus.OK)28 .payload("{\"name\":\"Raj\",\"salary\":10000}");29 echo("Validating the response payload");30 validate().json().schema("/home/raj/Downloads/schema.json");31 }32}33package com.consol.citrus.validation.json;34import java.io.IOException;35import org.testng.annotations.Test;36import com.consol.citrus.dsl.testng.TestNGCitrusTestRunner;37public class JsonSchemaValidation extends TestNGCitrusTestRunner{38 public void JsonSchemaValidation() throws IOException {39 http().client("httpClient")40 .send()41 http().client("httpClient")42 .receive()43 .response(HttpStatus.OK)44 .payload("{\"name\":\"Raj\",\"salary\":10000}");45 echo("Validating the response payload");46 validate().json().schema
JsonSchemaValidation
Using AI Code Generation
1package com.consol.citrus.samples;2import java.io.IOException;3import org.springframework.context.annotation.Bean;4import org.springframework.context.annotation.Configuration;5import com.consol.citrus.dsl.builder.BuilderSupport;6import com.consol.citrus.dsl.builder.DelegatingTestBehavior;7import com.consol.citrus.dsl.builder.TestBehavior;8import com.consol.citrus.dsl.builder.TestBehaviorBuilder;9import com.consol.citrus.dsl.builder.TestBehaviorChainBuilder;10import com.consol.citrus.dsl.builder.TestBehaviorChainBuilder.TestBehaviorChainBuilderSupport;11import com.consol.citrus.dsl.builder.TestBehaviorChainBuilder.TestBehaviorChainBuilderSupportImpl;12import com.consol.citrus.dsl.builder.TestBehaviorChainBuilder.TestBehaviorChainBuilderSupportImpl.TestBehaviorChainBuilderSupportImplBuilder;13import com.consol.citrus.dsl.builder.TestBehaviorChainBuilder.TestBehaviorChainBuilderSupportImpl.TestBehaviorChainBuilderSupportImplBuilder.TestBehaviorChainBuilderSupportImplBuilderImpl;14import com.consol.citrus.dsl.builder.TestBehaviorChainBuilder.TestBehaviorChainBuilderSupportImpl.TestBehaviorChainBuilderSupportImplBuilder.TestBehaviorChainBuilderSupportImplBuilderImpl.TestBehaviorChainBuilderSupportImplBuilderImplImpl;15import com.consol.citrus.dsl.builder.TestBehaviorChainBuilder.TestBehaviorChainBuilderSupportImpl.TestBehaviorChainBuilderSupportImplBuilder.TestBehaviorChainBuilderSupportImplBuilderImpl.TestBehaviorChainBuilderSupportImplBuilderImplImpl.TestBehaviorChainBuilderSupportImplBuilderImplImplBuilder;16import com.consol.citrus.dsl.builder.TestBehaviorChainBuilder.TestBehaviorChainBuilderSupportImpl.TestBehaviorChainBuilderSupportImplBuilder.TestBehaviorChainBuilderSupportImplBuilderImpl.TestBehaviorChainBuilderSupportImplBuilderImplImpl.TestBehaviorChainBuilderSupportImplBuilderImplImplBuilder.TestBehaviorChainBuilderSupportImplBuilderImplImplBuilderImpl;17import com.consol.citrus.dsl.builder.TestBehaviorChainBuilder.TestBehaviorChainBuilderSupportImpl.TestBehaviorChainBuilderSupportImplBuilder.TestBehaviorChainBuilderSupportImplBuilderImpl.TestBehaviorChainBuilderSupportImplBuilderImplImpl.TestBehaviorChainBuilderSupportImplBuilderImplImplBuilder.TestBehaviorChainBuilderSupportImplBuilderImplImplBuilderImpl.TestBehaviorChainBuilderSupportImplBuilderImplImplBuilderImplBuilder;18import com.consol.citrus.dsl.builder.TestBehaviorChainBuilder.TestBehaviorChainBuilderSupportImpl.TestBehaviorChainBuilderSupportImplBuilder.TestBehaviorChainBuilderSupportImplBuilderImpl.TestBehaviorChainBuilderSupportImplBuilderImplImpl.TestBehaviorChainBuilderSupportImplBuilderImplImplBuilder.TestBehaviorChainBuilder
JsonSchemaValidation
Using AI Code Generation
1public void testJsonSchemaValidation() {2 JsonTextMessageValidator jsonTextMessageValidator = new JsonTextMessageValidator();3 jsonTextMessageValidator.validateMessage(new JsonTextMessage("{ \"name\": \"John Doe\", \"age\": 45}"), new JsonTextMessage("{ \"name\": \"John Doe\", \"age\": 45}"), context);4}5public void testJsonSchemaValidation() {6 JsonTextMessageValidator jsonTextMessageValidator = new JsonTextMessageValidator();7 jsonTextMessageValidator.validateMessage(new JsonTextMessage("{ \"name\": \"John Doe\", \"age\": 45}"), new JsonTextMessage("{ \"name\": \"John Doe\", \"age\": 45}"), context);8}9public void testJsonSchemaValidation() {10 JsonTextMessageValidator jsonTextMessageValidator = new JsonTextMessageValidator();11 jsonTextMessageValidator.validateMessage(new JsonTextMessage("{ \"name\": \"John Doe\", \"age\": 45}"), new JsonTextMessage("{ \"name\": \"John Doe\", \"age\": 45}"), context);12}13public void testJsonSchemaValidation() {14 JsonTextMessageValidator jsonTextMessageValidator = new JsonTextMessageValidator();15 jsonTextMessageValidator.validateMessage(new JsonTextMessage("{ \"name\": \"John Doe\", \"age\": 45}"), new JsonTextMessage("{ \"name\": \"John Doe\", \"age\": 45}"), context);16}17public void testJsonSchemaValidation() {18 JsonTextMessageValidator jsonTextMessageValidator = new JsonTextMessageValidator();19 jsonTextMessageValidator.validateMessage(new JsonTextMessage("{ \"name\": \"John Doe\", \"age\": 45}"), new JsonTextMessage("{ \"name\": \"John Doe\", \"age\": 45}"), context);20}
JsonSchemaValidation
Using AI Code Generation
1public class JsonSchemaValidation {2public static void main(String[] args) {3JsonTextMessageValidator jsonValidator = new JsonTextMessageValidator();4JsonSchema schema = JsonSchemaFactory.byDefault().getJsonSchema("classpath:com/citrusframework/schema.json");5jsonValidator.setSchema(schema);6jsonValidator.validate(new JsonTextMessage("{\n" +7"{ \"name\":\"Ford\", \"models\":[\"Fiesta\", \"Focus\", \"Mustang\"] },\n" +8"{ \"name\":\"BMW\", \"models\":[\"320\", \"X3\", \"X5\"] },\n" +9"{ \"name\":\"Fiat\", \"models\":[\"500\", \"Panda\"] }\n" +10"}"));11}12}13public class JsonSchemaValidation {14public static void main(String[] args) {15JsonTextMessageValidator jsonValidator = new JsonTextMessageValidator();16JsonSchema schema = JsonSchemaFactory.byDefault().getJsonSchema("classpath:com/citrusframework/schema.json");17jsonValidator.setSchema(schema);18jsonValidator.validate(new JsonTextMessage("{\n" +19"{ \"name\":\"Ford\", \"models\":[\"Fiesta\", \"Focus\", \"Mustang\"] },\n" +20"{ \"name\":\"BMW\", \"models\":[\"320\", \"X3\", \"X5\"] },\n" +21"{ \"name\":\"Fiat\", \"models\":[\"500\", \"Panda\"] }\n" +22"}"));23}24}25public class JsonSchemaValidation {26public static void main(String[] args) {27JsonTextMessageValidator jsonValidator = new JsonTextMessageValidator();28JsonSchema schema = JsonSchemaFactory.byDefault().getJsonSchema("classpath:com/citrusframework/schema.json");29jsonValidator.setSchema(schema);30jsonValidator.validate(new JsonTextMessage("{\n" +
JsonSchemaValidation
Using AI Code Generation
1public void test() {2 ApplicationContext context = new ClassPathXmlApplicationContext("classpath:4.xml");3 Citrus citrus = Citrus.newInstance(context);4 citrus.run(new TestAction() {5 public void doExecute(TestContext context) {6 String jsonSchema = "{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"age\":{\"type\":\"number\"}}}";7 String json = "{\"name\":\"Raj\",\"age\":20}";8 JsonTextMessageValidator validator = new JsonTextMessageValidator();9 validator.validateMessagePayload(json, jsonSchema, context);10 }11 });12}
JsonSchemaValidation
Using AI Code Generation
1public void testJsonSchemaValidation() {2 run(new TestCase()3 .name("JsonSchemaValidation")4 .actions(5 .payload("{\"name\":\"John Doe\",\"age\":25}"),6 .validator(jsonSchemaValidation("classpath:com/consol/citrus/validation/json/JsonSchemaValidationTest.json"))7 );8}9public void testJsonSchemaValidation() {10 run(new TestCase()11 .name("JsonSchemaValidation")12 .actions(13 .payload("{\"name\":\"John Doe\",\"age\":25}"),14 .validator(jsonSchemaValidation("classpath:com/consol/citrus/validation/json/JsonSchemaValidationTest.json")15 .ignoreUnknownFields(true)16 .ignoreMissingFields(true))17 );18}19public void testJsonSchemaValidation() {20 run(new TestCase()21 .name("JsonSchemaValidation")22 .actions(23 .payload("{\"name\":\"John Doe\",\"age\":25}"),24 .validator(jsonSchemaValidation("classpath:com/consol/citrus/validation/json/JsonSchemaValidationTest.json")25 .ignoreUnknownFields(true)26 .ignoreMissingFields(true)27 .schemaValidation(true))28 );29}30public void testJsonSchemaValidation() {31 run(new TestCase()32 .name("JsonSchemaValidation")33 .actions(34 .payload("{\"name\":\"John Doe\",\"age\":25}"),35 .validator(jsonSchemaValidation("classpath:com/consol/citrus/validation/json/JsonSchemaValidationTest.json
JsonSchemaValidation
Using AI Code Generation
1public class 4 extends TestCase {2 public void 4() {3 variable("jsonSchema", "classpath:com/citrusframework/yaks/json/4.json");4 variable("jsonBody", "{\"id\": \"1\", \"name\": \"Citrus\", \"price\": 42.42}");5 http().client("httpClient")6 .send()7 .post("/test")8 .contentType("application/json")9 .payload("${jsonBody}");10 http().client("httpClient")11 .receive()12 .response(HttpStatus.OK)13 .messageType(MessageType.PLAINTEXT)14 .validator("jsonTextMessageValidator")15 .validate("$.id", "@ignore@")16 .validate("$.name", "@ignore@")17 .validate("$.price", "@isNumber@");18 }19}20public class 5 extends TestCase {21 public void 5() {22 variable("jsonSchema", "classpath:com/citrusframework/yaks/json/5.json");23 variable("jsonBody", "{\"id\": \"1\", \"name\": \"Citrus\", \"price\": 42.42}");24 http().client("httpClient")25 .send()26 .post("/test")27 .contentType("application/json")28 .payload("${jsonBody}");29 http().client("httpClient")30 .receive()31 .response(HttpStatus.OK)32 .messageType(MessageType.PLAINTEXT)33 .validator("jsonTextMessageValidator")34 .validate("$.id", "@ignore@")35 .validate("$.name", "@ignore@")36 .validate("$.price", "@isNumber@");37 }38}39public class 6 extends TestCase {40 public void 6() {41 variable("jsonSchema", "classpath:com/citrusframework/yaks/json/6.json");42 variable("jsonBody", "{\"id\": \"1\", \"name\": \"Citrus\", \"price\": 42.42}");43 http().client("httpClient")44 .send()45 .post("/test")46 .contentType("application/json")47 .payload("${jsonBody}");
JsonSchemaValidation
Using AI Code Generation
1public void testValidateJsonSchema() {2 http().client(httpClient)3 .send()4 .post("/api/v1/validateJsonSchema")5 .payload(new ClassPathResource("request.json"));6 http().client(httpClient)7 .receive()8 .response(HttpStatus.OK)9 .messageType(MessageType.JSON)10 .validate(JsonSchemaValidation.INSTANCE)11 .schema(new ClassPathResource("schema.json"));12}13public void testValidateXpathExpression() {14 http().client(httpClient)15 .send()16 .post("/api/v1/validateXpathExpression")17 .payload(new ClassPathResource("request.xml"));18 http().client(httpClient)19 .receive()20 .response(HttpStatus.OK)21 .messageType(MessageType.XML)22 .validate(XPathExpressionValidationContext.INSTANCE)23}24public void testValidateXpath() {25 http().client(httpClient)26 .send()27 .post("/api/v1/validateXpath")28 .payload(new ClassPathResource("request.xml"));29 http().client(httpClient)30 .receive()31 .response(HttpStatus.OK)32 .messageType(MessageType.XML)33 .validate(XpathMessageValidationContext.INSTANCE)34}35public void testValidateGroovyScript() {36 http().client(httpClient)37 .send()38 .post("/api/v1/validateGroovyScript")39 .payload(new ClassPathResource("request.json"));40 http().client(httpClient)41 .receive()42 .response(HttpStatus.OK)43 .messageType(MessageType.JSON)44 .validate(GroovyScriptValidationContext.INSTANCE)45 .script(new ClassPath
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!