Reputation: 5
I need to compare json response in beanshell sampler and print if the condition is passed or failed. Can someone please help, how do we compare it ? I already have a response in json format and one i will be getting another when the test is executed, i ned to compare those two word to word.
I tried using if/else but then its not working properly.
JSONObject JsonResponseinput = new JSONObject();
JsonResponseinput.toString();
print(JsonResponseinput + " = PASS");
f.close();
String s=JsonResponseinput.toString();
if (s == JsonResponse)
{
f = new FileOutputStream("output/path/API_OUTPUT.csv", true);
p = new PrintStream(f);
this.interpreter.setOut(p);
print(s + " = PASS");
f.close();
}
Else
{
print(JsonResponseinput + " = FAIL")
}
Upvotes: 0
Views: 2662
Reputation: 1
I use a tool called DeltaJSON from DeltaXML for JSON comparison there is a neat GUI and REST interface. You could use the REST API and parse the response.
Upvotes: 0
Reputation: 499
You can compare 2 JSON Response using following ways:
Use JSR223 Sampler to process the code in Script area
String response1 = vars.get("jsonOutput1");
String response2 = vars.get("jsonOutput2");
if (response1.equals(response2)) {
log.info("Responses are equal");
}
else {
log.info("Responses are not equal");
}
Upvotes: 1
Reputation: 167992
There are at least 4 ways of doing this:
Using Jackson like:
final JSONObject obj1 = /*json*/;
final JSONObject obj2 = /*json*/;
final ObjectMapper mapper = new ObjectMapper();
final JsonNode tree1 = mapper.readTree(obj1.toString());
final JsonNode tree2 = mapper.readTree(obj2.toString());
if (tree1.equals(tree2)) {
log.info('PASS');
}
else {
log.info('FAIL')
}
Using GSON like:
JsonParser parser = new JsonParser();
JsonElement o1 = parser.parse("{a : {a : 2}, b : 2}");
JsonElement o2 = parser.parse("{b : 2, a : {a : 2}}");
assertEquals(o1, o2);
Using JsonSlurper like:
def json1 = new groovy.json.JsonSlurper().parseText("json1")
def json2 = new groovy.json.JsonSlurper().parseText("json2")
if (json1 == json2) {
log.info('PASS')
} else {
log.info('FAIL')
}
Using JSONAssert like
try {
org.skyscreamer.jsonassert.JSONAssert.assertEquals("json1", "json2", false)
println('PASS')
}
catch (Exception ex) {
println('FAIL')
}
More information: The Easiest Way To Compare REST API Responses Using JMeter
P.S. Forget about Beanshell, since JMeter 3.1 you should be using JSR223 Test Elements and Groovy language for any form of scripting
Upvotes: 2