05 Validate Response - biswajitsundara/Karate GitHub Wiki

ValidateResponse.feature

Feature: Validate user response
  
  Scenario: Validate user response
    * url 'https://reqres.in'
    * def expectedoutput = read('./data/data.json')
    
    Given path '/api/users/2'
    When method GET
    Then status=200
    And match response == expectedoutput
    And match response.data.id == 2
    And match response.data.last_name != null
    * def job_code = response.data.job_code
    And match job_code == null

data.json

{
	"data": {
		"last_name": "Weaver",
		"id": 2,
		"avatar": "https://reqres.in/img/faces/2-image.jpg",
		"first_name": "Janet",
		"email": "[email protected]"
	},
	"support": {
		"text": "To keep ReqRes free, contributions towards server costs are appreciated!",
		"url": "https://reqres.in/#support-heading"
	}
}

ValidateTestRunner.java

import org.junit.runner.RunWith;
import com.intuit.karate.junit4.Karate;

@RunWith(Karate.class)
public class ValidateTestRunner {

}

Explanation

  • We know from Basic.feature file, for declaring any variable step we use any keyword means *
  • def expectedoutput means we have declared the variable expectedoutput
  • read(file name within single quote) is how we read files
  • so basically the step * def expectedoutput = read('data.json') is
  • reading the file from data.json & storing it in variable expectedoutput

  • match response == expectedoutput means it is trying to compare the response
  • with the string that is in expectedoutput variable.
  • Instead of external file, we can also validate the response in feature file itself
  • we will have to write this way, match response == 'response string in single line'
  • please note the response string has to be in one line. To convert a JSON array
  • from multiple lines to single line we can use this website
  • https://tools.knowledgewalls.com/jsontostring
  • But having the response in external file is the best practice.

  • If we want to check a particular field in the respnse
  • Then we will follow the hierarchy response.data.id in this example
  • And then compare the value.
  • Let's say we want to compare the whole response but want to ignore
  • a particular field then in the data.json we can modify this way
  • Before : "first_name": "Janet",
  • After : "first_name": "#ignore",
  • Then it will validate for all other fields except this one.
  • But it will check whether the field is available or not.
  • only value comparison won't happen.

  • If we want to check the field is available in the response
  • check this way : response.data.last_name != null
  • If we want to check the field is not available in the response
  • first store the response in a variable, if the field is not available
  • then it will return null & then compare that value with null
  • if both matches means the field doesn't exist.
  • refer the job_code example above
⚠️ **GitHub.com Fallback** ⚠️