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")
}
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