Forum Discussion

sonya_m's avatar
sonya_m
SmartBear Alumni (Retired)
5 years ago

[TechCorner Challenge #6] How to Generate Email When Assertion Fails

Hello Community!   Today we have another task for you to help contribute to our collection of useful ReadyAPI content. Here is the task: Create a Groovy script that will send an ...
  • groovyguy's avatar
    groovyguy
    5 years ago

    Task: Create a Groovy script that will send an email when an assertion fails

     

    This is a solution created for [TechCorner Challenge #6]

     

    I thought I posted a reply but it disappeared.

     

     

    // set project reference
    def project = context.project;
    
    // set testTypes. Can expand for more test step types that allow assertions.
    def testTypes = [com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep, com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep];
    
    // start an error list.
    def errors = [];
    
    // Walk through the test suites, test cases, and test steps.
    for (ts in project.getTestSuiteList())
    {
    	for (tc in ts.getTestCaseList())
    	{
    		for (testType in testTypes)
    		{
    			for (step in tc.getTestStepsOfType(testType))
    			{
    				for (assertion in step.getAssertionList())
    				{
    					if (assertion.errors != null)
    					{
    						def errorMsg = ts.getName() + " - " + tc.getName() + " - " + step.getName();
    						errorMsg += " has failed with the error: " + assertion.errors.toString();
    						errors.add(errorMsg);
    					}
    				}
    			}
    		}
    	}
    }
    
    if (errors != [])
    {
    	// def sendMail = context.project.testSuites["TestSuiteWithSendMail"].testCases["TestCaseWithSendMail"].testSteps["Send Mail"];
    	def body = "";
    	for (error in errors)
    	{
    		body+= error + "\n";
    	}
    	def sendMail = context.testCase.testSteps["Send Mail"];
    	sendMail.setMessage(body);
    	sendMail.setSubject("Project run Errors");
    	sendMail.run(context.testRunner, context);
    }