Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON validation using JSONAssert with regular expressions

I am working in a open-source project which uses REST interface. To validate (match actual response with expected) our rest interfaces in the JUnit, we would like to use the JSONAssert. (https://github.com/skyscreamer/JSONassert). But I have a problem with the usage.Kindly help to resolve it.

Expected JSON:
{
"objectId": "[^\\s]",
"protocol": "[^\\s]",
"hostName": "[^\\s]",
"port": "[^\\s]",
"commParams": "[^\\s]"
}

Remarks: objectId/protocol/hostName/port/commParams can be anything but should not be empty

Actual JSON:
{
"objectId": "controller2",
"protocol": "ftp",
"hostName": "sdnorchestrator",
"port": "21",
"commParams": "username:tomcat, password:tomdog"
}

Problem1: Which interface of JSON Assert, i need to use to solve the above issue:Below one?

JSONAssert.assertEquals("Expected JSON", "Actual JSON" new CustomComparator(
    JSONCompareMode.LENIENT_ORDER, new Customization(PREFIX, new        RegularExpressionValueMatcher<Object>())));

Problem 2: What should be the PREFIX here?(I tried with "", "., "." but had no success)

Any other recommendation (other than JSONAssert) for the above problem is also welcome.

like image 407
Murali Mohan Murthy Potham Avatar asked Aug 08 '16 07:08

Murali Mohan Murthy Potham


1 Answers

If you want to globally apply regular expression customizations with JSONAssert, you can construct a single Customization with path = "***", and use the RegularExpressionValueMatcher constructor with no arguments.

Example:

final String expectedJson = "{objectId: \"[^\\s]+\", protocol: \"[^\\s]+\"}";
final String actualJson = "{\"objectId\": \"controller2\", \"protocol\": \"ftp\"}";

JSONAssert.assertEquals(
    expectedJson,
    actualJson,
    new CustomComparator(
        JSONCompareMode.LENIENT,
        new Customization("***", new RegularExpressionValueMatcher<>())
    )
);

This assertion passes successfully (tested with JSONassert version 1.5.0).

like image 58
Alex Shesterov Avatar answered Oct 16 '22 16:10

Alex Shesterov