Archive for the ‘xPath’ Category

Many of the blog readers have asked this question in past “How to create a dynamic XPath assertion?”. And almost everybody had it’s own explanation about the word Dynamic [with Xpath]. So here i am sharing my understanding on the same :

For me a ‘dynamic assertion’ is one which automatically changes the expected result based on my Request input. For instance (referring to Weather Forecast webservice), if i am requesting the weather data for “Jodhpur, India” then my response should contain “Jodhpur” in the <City Name> tag. Similarly, if i request “Bangalore, India” then response will contain “Bangalore” in the <City Name> tag.

Let’s elaborate the given example & find out how a Regular xPath assertion is added. And then we will modify our existing assertion into a Dynamic assertion.

<!-- My request looks like following -->
<Request>
<WeatherByCity>
<CityName>Jodhpur</CityName>
<CountryName>India</CountryName>
</WeatherByCity>
</Request>

 

<!-- Response for the above request -->

<Response>
<WeatherByCity>
 <CityName>Jodhpur</CityName>
<Weather>
<Temperature>45</Temperature>
<DegreeUnit>Celsius</DegreeUnit>
<Detail>Sunny Weather</Detail>
</Weather>
</WeatherByCity>
</Response>

So, now we have both the request & response available with us. How about you try putting some xPath assertion over the response? Something like the cityName=”Jodhpur” and DegreeUnit=”Celsius” etc. I guess that was easy? Anyways, here is my solution :

<!-- xpath expression to fetch the value of City Name from the response -->
//WeatherByCity/CityName

<!-- expected result value should be equal to -->
Jodhpur

Now change the input request data (i.e., CityName) to Bangalore. And hit the same request again. See it is failing. Did you observed this? This failure of the test request occurred due to the failure of earlier added xPath assertion. So to test the same request (with different data) either i have to create multiple copies of the request and modify the assertion accordingly. Or modify the assertion everytime whenever i change the request data. Now this sounds very painful. Here is the approach to make life simpler.

Put the following code in the expected result :

<!-- expected result value should be equal to -->
${myTestStepRequestName#Request#//WeatherByCity/CityName}
Now this is simpler and more useful. It is just using the regular “Property Expansion” code and that would be evaluated during execution of assertion method call. No need to change the assertion content over and over again for a change in request content data.
BTW, the same approach can be used in the “Contains”, “Not Contains” and few other assertion also. Or maybe you can store your result (expected data) in a property test step and match them using this approach.
Till next blog, happy reading and happy sharing 🙂
Advertisements