Forum Discussion

kaivi's avatar
kaivi
Contributor
7 years ago

compare a response with a json file

Hey,

 

first of all i have a GET request with a response... now i wanna save the response in a JSON file to compare this with a existing JSON file.

 

HOW can i do this?

 

best regards

kai

  • You can use the following code:

     

    ...
    if (!(it.value == outputResp[it.key]))
        {
            log.info ("File Mismatch at : " + it.key)
            testRunner.fail( "File mismatch..." )
        }
    ...
  • Lucian's avatar
    Lucian
    Community Hero

    This should be simple to do. But just to clarify before giving an answer:

     

    1. If you want to compare the response with an existing content of a file why do you want to save the response to a file. Wouldn't it be simpler to just read the content of the initial file and compare it directly with the current response.

    2. I am not aware of the full context of your test but I generally see this kind of tests unreliable. If something is to change in the response you may have to do a lot of rework.

    • kaivi's avatar
      kaivi
      Contributor

      1.Yes. Is that possible?

      2. True!

       

      i found some Code and it works but maybe u can help me. If there is a Mismatch there is only a log.info and the test continues with "PASS". Is taht possible to say is there a mismatch the test failed?

       

      import groovy.json.JsonSlurper
      def filePath = "C:/qwerty/test.json"
      def jsonResp = context.expand('${GET ProCon#Response}') 
      
      def outputResp = new JsonSlurper().parseText(jsonResp)
      def baselineResp = new JsonSlurper().parseText(new File(filePath).text)
      
      baselineResp.each{
      
          if (!(it.value == outputResp[it.key]))
          {
              log.info ("File Mismatch at : " + it.key)
          }
      
      }
      • jhanzeb1's avatar
        jhanzeb1
        Frequent Contributor

        You can use a keyword assert i.e assert expected == actual