Forum Discussion

hindza's avatar
hindza
New Contributor
7 years ago
Solved

Help adding Assertions with Groovy Script

Hi gents,    First time poster here, I am in desperate need of your help. I've tried scouring the web trying to find a simple solution to my problem, but haven't been able to find it. I am a total ...
  • hindza's avatar
    7 years ago

    I've managed to find an answer for my problem. 

    I've also added two new assertions, one for adding Valid HTTP Status Codes and another for Invalid, as I learned this is a good practice when testing REST API's. 

    //This part adds the Invalid HTTP Status Codes in an Assertion targeting the named Test Step.
    //Status codes can be added or removed as it suits your needs.
    def InvalidAssertion = testRunner.testCase.testSteps["Test Step Name"].addAssertion("Invalid HTTP Status Codes");
    java.lang.reflect.Field InvalidStatusAssertionCodesField = InvalidAssertion.getClass().getDeclaredField("codes");
    InvalidStatusAssertionCodesField.setAccessible(true);
    InvalidStatusAssertionCodesField.set(InvalidAssertion, "400,401,402,403,404,500")
    
    //This part adds the Valid HTTP Status Codes in an Assertion targeting the named Test Step.
    //Status codes can be added or removed as it suits your needs.
    def ValidAssertion = testRunner.testCase.testSteps["Test Step Name"].addAssertion("Valid HTTP Status Codes");
    java.lang.reflect.Field ValidStatusAssertionCodesField1 = ValidAssertion.getClass().getDeclaredField("codes");
    ValidStatusAssertionCodesField.setAccessible(true);
    ValidStatusAssertionCodesField.set(ValidAssertion, "200")
    
    //This part takes the Request from the targeted Test Step and displays it onscreen as a string.
    //Then it adds an Assertion of the "Contains" type and inserts the string (from the previous step) into the targeted Test Step.
    def Request = testRunner.testCase.getTestStepByName('Test Step Name').testRequest.response.contentAsString
    log.info(Request)
    def Assertion = testRunner.testCase.testSteps["Test Step Name"].addAssertion("Contains")
    Assertion.setToken(Request)

    This now constitutes a "block" of code that can be used for each of the Test Steps. 
    However, I have 1300 Test Steps and can't change every one by had. I used an excel sheet to create a list of these blocks and just copy the needed blocks into a Groovy Step. Then I run all the Test Steps, to get the Responses, then run the Groovy Step and it fills out all the Test Steps with corresponding data. The Groovy Step can be manually executed even if it's disable, which is great!

    After all of that I run the whole Test Case or Test Suite and look if everything is as expected. 

     

    If you need more details on creating a block list please ask, I won't post it now as it'll take too much time, and is not relevant to the topic.  

     

    Thanks for reading.