Hit a URL using groovy step - groovy

I created a HTTP request step and checked the response code 200/400 .
The same i want to check using groovy only. No HTTP requeststep. Use only groovy step.
URL response script:-
def rawResponse = new String(testRunner.testCase.testSteps["HTTP Request"].testRequest.response.rawResponseData)
log.info rawResponse
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def httpResponseHeaders = context.testCase.testSteps["HTTP Request"].testRequest.response.responseHeaders
def httpStatus = httpResponseHeaders["#status#"]
def httpStatusCode = (httpStatus =~ "[1-5]\\d\\d")[0]
log.info("HTTP status code: " + httpStatusCode)
if (httpStatusCode == "200")
{
log.info "Success"
}
else
{
log.info "Failure"
}

Related

How to run SoapUI teststeps in parrallel with Groovy

SoapUI has options to run your test-suites and test-cases in parallel but no such thing for doing it with test-steps.
How can I achieve such a thing with a Groovy teststep inside my testcase?
This is my current code:
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner
//Get all Soap type test steps within the testCases
for ( testStep in testRunner.testCase.getTestStepsOfType(com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep.class)){
//Print out the name for the testStep
tsname = testStep.getName();
log.info tsname;
//thread = new Thread("$tsname")
def th = new Thread("$tsname") {
#Override
public void run(){
//Set the TestRunner to the respective TestCase
TestRunner = new com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner(testRunner.testCase, null);
//Run them all and then rejoin the threads
log.info("thread: " + tsname)
TestRunner.runTestStepByName(tsname);
def soapResponse = TestRunner.getTestCase().getTestStepByName(tsname).getProperty("Response");
log.info "soapResponse: " + soapResponse;
th.join();
}
}
th.start();
th.join();
}
Managed to fix it myself and posted the answer here for all who stumble into the same problem:
import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep
List<String> steps = testRunner.testCase.getTestStepsOfType(com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep.class)
def map = [:]
//define the threads list, this will hold all threads
def threads = []
def kickEm = steps.each{ step ->
def th = new Thread({
stepName = step.getName();
log.info "Thread in start: " + step.getName();
//Set the TestRunner to the respective TestCase
TestRunner = new com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner(testRunner.testCase, null);
//Run the corresponding teststep
TestRunner.runTestStepByName(step.getName());
//Get the response of the current step
def soapResponse = context.expand(TestRunner.getTestCase().getTestStepByName(step.getName()).getPropertyValue('Response')) as String;
log.info "In thread "+step.getName()+" soapResponse: " + soapResponse
//Put this into a map, the key is the stepname and the value is its response, so we can retrieve it all outside the each loop
map.put(step.getName(), soapResponse);
})
log.info "Putting new Thread({..}) th back into the threads list";
threads << th;
}
threads.each { it.start(); }
threads.each { it.join(); }
log.info "Map: "
map.each { step, response ->
log.info "Step: ${step} has the response ${response}"
};
log.info "Done!"

Creating a Test Report in SoapUI from Project level tear down script

I tried to change the code that #Rao wrote, here's a link! to show the details of the Test Steps in the report, unfortunately it does not work. Could someone help?
My question is really on syntax, I want to develop a report when the whole project is run, it outputs the following results:
Project Name - is it success or failed. If one suite failed then project fails else it passes
Test Suite - Take name of each test suite in project and if passes then place 'Succeed' next to name of test suite else place 'Failed' next to name of test suite
Name of all test cases within test suite. Like the one in screenshot really, 'succeed' next to test cases that have passed and 'failed' next to those that haven't.
Test Step- Take name of each test step in project and if passes then place 'Succeed' next to name of test step else place 'Failed' next to name of test step
Finally the property values. If a test case has failed, capture the property values for that failed test case so we can track which values were entered that caused the failure of the test
Below is the code:
/**
*
* Below is the TearDown script for SoapUI Project level
* Which create a custom report in a given file
* Modify the variable "reportFileName" below
*
**/
//Modify the file as needed for report file
//def reportFileName = '/tmp/abctestreport.txt'
//Adding the below as user wants specific directory
//Get the project path
def dataFolder = new com.eviware.soapui.support.GroovyUtils(context).projectPath
//Create today's date for storing response
def today = new Date().format("yyyy-MM-dd")
def filePrefix = "${dataFolder}/TestReports/Local_AllModules_Report_${today}" as String
def fileNamePart = new Date().format("yyyy-MM-dd'T'HH.mm.ss")
//creating filename dynamically.
def reportFileName = "${filePrefix}/Local_AllModules_TestReport_${fileNamePart}.txt" as String
//NOTE: Not required to edit beyond this point
/**
* This class holds the test step details
**/
class TestStepResultHolder {
def log
Map<String, String> propertiesTest = [:]
boolean status
def getTestStepList(testCase) {
testCase.getTestCase().each { key ->
propertiesTest[key] = testCase.getTestStepByName(key)
}
}
def getStepResult(stepRunner, stepName) {
log.info "Checking test case status ${stepName}"
if ( stepRunner.status.toString() == 'FAILED' ){
log.error "Test case $stepName has failed"
for ( step_Result in stepRunner?.results ){
step_Result.messages.each() { msg -> log.info msg }
}
return false
} else {
log.info "${stepName} is passed"
}
true
}
def buildStepResult(stepRunner, stepName) {
status = getStepResult(stepRunner, stepName)
if (!status) {
createProperties(stepRunner.testCase)
}
}
}
/**
* This class holds the test case details
**/
class TestCaseResultHolder {
def log
Map<String, String> properties = [:]
boolean status
def createProperties(testCase) {
testCase.getPropertyNames().each { key ->
properties[key] = testCase.getPropertyValue(key)
}
}
def getCaseResult(caseRunner, caseName) {
log.info "Checking test case status ${caseName}"
if ( caseRunner.status.toString() == 'FAILED' ){
log.error "Test case $caseName has failed"
for ( stepResult in caseRunner?.results ){
stepResult.messages.each() { msg -> log.info msg }
}
return false
} else {
log.info "${caseName} is passed"
}
true
}
def buildCaseResult(caseRunner, caseName) {
status = getCaseResult(caseRunner, caseName)
if (!status) {
createProperties(caseRunner.testCase)
}
}
}
/**
* This class holds the test suite details
**/
class SuiteResultsHolder {
def log
Map<String, TestCaseResultHolder> casaeResults = [:]
int testCaseCount = 0
int passedCasesCount = 0
int failedCasesCount = 0
def buildSuiteResults(suiteRunner, suiteName){
log.info "Building results of test suite ${suiteName}"
for ( caseRunner in suiteRunner?.results ) {
def caseName = caseRunner.testCase.name
testCaseCount++
def tcHolder = new TestCaseResultHolder(log: log)
tcHolder.buildCaseResult(caseRunner, caseName)
casaeResults[caseName] = tcHolder
if (tcHolder.status) {
passedCasesCount++
} else {
failedCasesCount++
}
}
}
def getStatus() {
(0 < failedCasesCount) ? false : true
}
}
/**
* This class holds the project details
**/
class ProjectResultsHolder {
def log
Map<String, SuiteResultsHolder> suiteResults = [:]
int suiteCount = 0
int passedSuitecount = 0
int failedSuiteCount = 0
def buildProjectResults(projectRunner, projectName) {
log.info "Building results of test project ${projectName}"
for(suiteRunner in projectRunner?.results) {
def suiteName = suiteRunner.testSuite.name
suiteCount++
def suiteResultsHolder = new SuiteResultsHolder(log: log)
suiteResultsHolder.buildSuiteResults(suiteRunner, suiteName)
suiteResults[suiteName] = suiteResultsHolder
if (suiteResultsHolder.status) {
passedSuitecount++
} else {
failedSuiteCount++
}
}
}
def getStatus() {
(0 < failedSuiteCount) ? false : true
}
}
//Get the status string based on boolean
def getResult(status){ status == true ? 'SUCCEED' : 'FAILED'}
//Draws a line
def drawLine(def letter = '=', def count = 70) { letter.multiply(count)}
//Gets the summary report
def getSummaryReport(project, projectResultHolder) {
def report = new StringBuffer()
report.append(drawLine()).append('\n')
report.append("\t\t\tTest Execution Summary\n")
report.append(drawLine('-', 60)).append('\n')
report.append("Project : ${project.name}\n")
report.append("Result : ${getResult(projectResultHolder.status)}\n")
report.append("Total test suites executed: ${projectResultHolder.suiteCount}\n")
report.append("Test suites passed: ${projectResultHolder.passedSuitecount}\n")
report.append("Test suites failed: ${projectResultHolder.failedSuiteCount}\n")
report.append(drawLine()).append('\n')
report
}
//Gets the test case report
def getTestCaseReport(testCaseReport) {
def report = new StringBuffer()
report.append(drawLine('-', 60)).append('\n')
report.append("\t\tTest Case Details:\n")
report.append(drawLine('-', 60)).append('\n')
testCaseReport.each { kase, tcReport ->
report.append("Name : ${kase}\n")
report.append("Status : ${getResult(tcReport.status)}\n")
if (!tcReport.status) {
report.append("Properties : ${tcReport.properties.toString()}\n")
}
}
report
}
//Gets the test step report
def getTestStepReport(testStepReport) {
def report = new StringBuffer()
report.append(drawLine('-', 60)).append('\n')
report.append("\t\tTest Case Details:\n")
report.append(drawLine('-', 60)).append('\n')
testStepReport.each { kaset, tsReport ->
report.append("Name : ${kaset}\n")
report.append("Status : ${getResult(tsReport.status)}\n")
if (!tsReport.status) {
report.append("Properties : ${tsReport.propertiesTest.toString()}\n")
}
}
report
}
//Get the detailed report
def getDetailedReport(projectResultHolder) {
def report = new StringBuffer()
report.append(drawLine()).append('\n')
report.append("\t\t\tTest Execution Detailed Report\n")
report.append(drawLine()).append('\n')
projectResultHolder.suiteResults.each { suite, details ->
report.append("Test Suite : ${suite}\n")
report.append("Result : ${getResult(details.status)}\n")
report.append("Total Cases : ${details.testCaseCount}\n")
report.append("Cases Passed : ${details.passedCasesCount}\n")
report.append("Cases Failed: ${details.failedCasesCount}\n")
report.append(getTestCaseReport(details.casaeResults))
report.append(drawLine()).append('\n')
report.append(drawLine()).append('\n')
}
report
}
//Save the contents to a file
def saveToFile(file, content) {
if (!file.parentFile.exists()) {
file.parentFile.mkdirs()
log.info "Directory did not exist, created"
}
file.write(content)
assert file.exists(), "${file.name} not created"
}
def holder = new ProjectResultsHolder(log: log)
holder.buildProjectResults(runner, project.name)
def finalReport = new StringBuffer()
finalReport.append(getSummaryReport(project, holder))
finalReport.append(getDetailedReport(holder))
def reportFile = new File(reportFileName)
saveToFile(reportFile, finalReport.toString())
To get test step result you may add a script like the one I use in your testcase's teardown script:
log.info "nb steps : " + testRunner.getTestCase().getTestStepCount()
for (testStep in testRunner.getResults()){
log.info "step " + testStep.getTestStep().getName() + " : " + testStep.getStatus()
}
You can also add the following in the testsuite's teardown script but when you run at testsuite level you will not get testcase's teardown scripts:
log.info "*********** EXECUTION SUMMARY *****************************************"
def runner = context.testRunner;
//log.info "nb test results = " + runner.getResultCount()
for (testRun in runner.getResults())
{
testCase = testRun.getTestCase()
//log.info "testCase " + testCase
log.info context.expand( '${#Project#testcase_flag}' ) + testCase.getName()
log.info "nb test steps = "+ testCase.getTestStepCount()
for (testResult in testRun.getResults())
log.info testResult.getTestStep().getName() + " : " + testResult.getStatus()
log.info context.expand( '${#Project#testcase_status_flag}' ) + " : " + runner.getStatus()
}
log.info "*************************************************************************************"
This works pretty well for me ...

Unable to retrieve data from an xml to place in an array

I am trying to retrieve a number of flightids from an xml and place them in an array but I keep getting no data displayed. It doesn't seem to find 'flights' but I am not sure why, is there anything wrong with the code below?
import groovy.xml.XmlUtil
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def response = context.expand( '${SOAP Request#Response}' )
def parsedxml = new XmlSlurper().parseText(response)
def tests= parsedxml.'**'.findAll { it.name() == 'b:TestId'}
log.info tests
//Get the rate plan codes
def testId = { option ->
def res = option.'**'.findAll {it.name() == 'b:TestId'}
if (res) return option.TestId.text()
null
}
def testIdArray = []
tests.each { if (testId(it)) testIdArray << testId(it) }
for (int i = 0; i < testIdArray.size(); i++) {
log.error "TestIds: " + testIdArray[i]
}
log.warn testIdArray.size()
Below is the xml:
<s:Envelope xxx="xxx" xxx="xxx">
<s:Header>
<a:Action s:mustUnderstand="1">xxx</a:Action>
</s:Header>
<s:Body>
<XML1 xmlns="xxx">
<XML2 xmlns:b="xxx" xmlns:i="xxx">
<XML3>
<b:TestId>000000</b:TestId>
</XML3>
<XML3>
<b:TestId>000000</b:TestId>
</XML3>
</XML2>
</XML1>
</s:Body>
</s:Envelope>
Pass the xml string response to below response variable
def xml = new XmlSlurper().parseText(response)
def getFlightIds = { type = '' ->
type ? xml.'**'.findAll { it.name() == type }.collect { it.FlightId.text() } : xml.'**'.findAll {it.FlightId.text()}
}
//Get the respective flight ids
//Use the desired one as you have mentioned none
def inFlightIds = getFlightIds('InboundFlightInformation')
def outFlightIds = getFlightIds('OutboundFlightInformation')
def allFlightIds = getFlightIds()
log.info "Inbound flight ids: ${inFlightIds}"
log.info "Outbound flight ids: ${outFlightIds}"
log.info "All flight ids: ${allFlightIds}"
You can quickly try online Demo
it.name() in your case it is a NodeChild
so, it.name() returns just a name without prefix. it means you should compare it to FlightId (without b: )
if you want to check a namespace (linked to a prefix) then your lookup must be like this:
def flights = parsedxml.'**'.findAll { it.name() == 'FlightId' && it.namespaceURI()=='xxx' }

Creating a Test Report from Project level tear down script

I have generate a report based on an execution of a test suite where it creates a folder directory and insert a file displaying the report. This is compiled within a TearDown Script at Test Suite level. Below is the code:
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def dataFolder = groovyUtils.projectPath
def failedTestCases = 0
def succeedTestCases = 0
def totalTestCases = 0
def testCaseFailed = ""
def testCaseSucceed = ""
def date = new Date()
def folderTime = date.format("yyyy-MM-dd HH-mm-ss")
def hotelId = context.getProperty('hotelid')
def hotelname = context.getProperty('hotelname')
def hoteltype = context.getProperty('hoteltype')
//def propertyValues = ""
//def correlationid = messageExchange.modelItem.testStep.testCase.testSuite.Project.namegetPropertyValue("correlationid")
//Create a folder directory for the responses
RootResultFolder = dataFolder + "\\Test Reports" + "\\xxx_WebAPI - " + folderTime + "\\"
CreateResultFolder = new File(RootResultFolder)
CreateResultFolder.mkdir()
//context.setProperty("RootResultFolder", RootResultFolder)
def fileName = "WebAPI Test Report.txt"
def rootFolder = RootResultFolder + fileName
def logFile = new File(rootFolder)
if(logFile.exists())
{
log.info("Error a file named " + fileName + "already exisits")
}
else
{
runner.results.each { testCaseResult ->
def name = testCaseResult.testCase.name
totalTestCases++
if(testCaseResult.status.toString() == 'FAILED'){
failedTestCases ++
testCaseFailed += "- $name - HAS FAILED \n\n"
//propertyValues += "hotelid - $hotelid, hotelname - $hotelname, hoteltype - $hoteltype \n\n"
testCaseResult.results.each{ testStepResults ->
testStepResults.messages.each() { msg -> log.info msg }
}
}else{
succeedTestCases ++
testCaseSucceed += "- $name - SUCCEED \n\n"
testCaseResult.results.each{ testStepResults ->
testStepResults.messages.each() { msg -> log.info msg }
}
}
}
}
logFile.write "TOTAL TEST CASES SUCCEED: $succeedTestCases of $totalTestCases" + "\n\n" +
testCaseSucceed + "---\n\n" +
"TOTAL TEST CASES FAILED: $failedTestCases of $totalTestCases" + "\n\n" +
testCaseFailed + "\n\n"
What I actually want to do is move the code from Test Suite level and place it in the tear down script at Project level. Now when I run the code from there, it does not generate the file, I'm assuming I need to place the correct paths in as I am not moving to test suite to test case but from project to test suite to testcase to test steps.
My question is really on syntax, I want to develop a report when the whole project is run, it outputs the following results:
Project Name - is it success or failed. If one suite failed then project fails else it passes
Test Suite - Take name of each test suite in project and if passes then place 'Succeed' next to name of test suite else place 'Failed' next to name of test suite
Name of all test cases within test suite. Like the one in screenshot really, 'succeed' next to test cases that have passed and 'failed' next to those that haven't.
Finally the property values. If a test case has failed, capture the property values for that failed test case so we can track which values were entered that caused the failure of the test.
Can somebody help me with the relevant syntax to perform these so then I can peice it into my code and manipulate?
UPDATE:
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def dataFolder = groovyUtils.projectPath
def date = new Date()
def folderTime = date.format("yyyy-MM-dd HH-mm-ss")
//Create a folder directory for the responses
RootResultFolder = dataFolder + "\\Test Reports" + "\\xxx - " + folderTime + "\\"
CreateResultFolder = new File(RootResultFolder)
CreateResultFolder.mkdir()*/
//context.setProperty("RootResultFolder", RootResultFolder)
def reportFileName = "WebAPI Test Report.txt"
def rootFolder = RootResultFolder + reportFileName
def logFile = new File(rootFolder)
If you look at the TearDown Script of the project, it shows as below i.e., the variables already initialized by soapui.
Issue with your script
So if you look at it, there is runner variable. Also the same variable is available at TearDown script of test suite level. But, these are instances of different Objects. The script used in OP was of suite level which you aware and that is why you are not seeing in the result.
Here is the project level TearDown Script and following in line comments.
/**
*
* Below is the TearDown script for SoapUI Project level
* Which create a custom report in a given file
* Modify the variable "reportFileName" below
*
**/
//Modify the file as needed for report file
//def reportFileName = '/tmp/abctestreport.txt'
//Adding the below as user wants specific directory
//Get the project path
def dataFolder = new com.eviware.soapui.support.GroovyUtils(context).projectPath
//Create today's date for storing response
def today = new Date().format("yyyy-MM-dd")
def filePrefix = "${dataFolder}/TestReports/xxx_WebAPI_${today}" as String
def fileNamePart = new Date().format("yyyy-MM-dd'T'HH.mm.ss")
//creating filename dynamically.
def reportFileName = "${filePrefix}/xxx_WebAPI_TestReport_${fileNamePart}.txt" as String
//NOTE: Not required to edit beyond this point
/**
* This class holds the test case details
**/
class TestCaseResultHolder {
def log
Map<String, String> properties = [:]
boolean status
def createProperties(testCase) {
testCase.getPropertyNames().each { key ->
properties[key] = testCase.getPropertyValue(key)
}
}
def getCaseResult(caseRunner, caseName) {
log.info "Checking test case status ${caseName}"
if ( caseRunner.status.toString() == 'FAILED' ){
log.error "Test case $caseName has failed"
for ( stepResult in caseRunner?.results ){
stepResult.messages.each() { msg -> log.info msg }
}
return false
} else {
log.info "${caseName} is passed"
}
true
}
def buildCaseResult(caseRunner, caseName) {
status = getCaseResult(caseRunner, caseName)
if (!status) {
createProperties(caseRunner.testCase)
}
}
}
/**
* This class holds the test suite details
**/
class SuiteResultsHolder {
def log
Map<String, TestCaseResultHolder> casaeResults = [:]
int testCaseCount = 0
int passedCasesCount = 0
int failedCasesCount = 0
def buildSuiteResults(suiteRunner, suiteName){
log.info "Building results of test suite ${suiteName}"
for ( caseRunner in suiteRunner?.results ) {
def caseName = caseRunner.testCase.name
testCaseCount++
def tcHolder = new TestCaseResultHolder(log: log)
tcHolder.buildCaseResult(caseRunner, caseName)
casaeResults[caseName] = tcHolder
if (tcHolder.status) {
passedCasesCount++
} else {
failedCasesCount++
}
}
}
def getStatus() {
(0 < failedCasesCount) ? false : true
}
}
/**
* This class holds the project details
**/
class ProjectResultsHolder {
def log
Map<String, SuiteResultsHolder> suiteResults = [:]
int suiteCount = 0
int passedSuitecount = 0
int failedSuiteCount = 0
def buildProjectResults(projectRunner, projectName) {
log.info "Building results of test project ${projectName}"
for(suiteRunner in projectRunner?.results) {
def suiteName = suiteRunner.testSuite.name
suiteCount++
def suiteResultsHolder = new SuiteResultsHolder(log: log)
suiteResultsHolder.buildSuiteResults(suiteRunner, suiteName)
suiteResults[suiteName] = suiteResultsHolder
if (suiteResultsHolder.status) {
passedSuitecount++
} else {
failedSuiteCount++
}
}
}
def getStatus() {
(0 < failedSuiteCount) ? false : true
}
}
//Get the status string based on boolean
def getResult(status){ status == true ? 'SUCCEED' : 'FAILED'}
//Draws a line
def drawLine(def letter = '=', def count = 70) { letter.multiply(count)}
//Gets the summary report
def getSummaryReport(project, projectResultHolder) {
def report = new StringBuffer()
report.append(drawLine()).append('\n')
report.append("\t\t\tTest Execution Summary\n")
report.append(drawLine('-', 60)).append('\n')
report.append("Project : ${project.name}\n")
report.append("Result : ${getResult(projectResultHolder.status)}\n")
report.append("Total test suites executed: ${projectResultHolder.suiteCount}\n")
report.append("Test suites passed: ${projectResultHolder.passedSuitecount}\n")
report.append("Test suites failed: ${projectResultHolder.failedSuiteCount}\n")
report.append(drawLine()).append('\n')
report
}
//Gets the test case report
def getTestCaseReport(testCaseReport) {
def report = new StringBuffer()
report.append(drawLine('-', 60)).append('\n')
report.append("\t\tTest Case Details:\n")
report.append(drawLine('-', 60)).append('\n')
testCaseReport.each { kase, tcReport ->
report.append("Name : ${kase}\n")
report.append("Status : ${getResult(tcReport.status)}\n")
if (!tcReport.status) {
report.append("Properties : ${tcReport.properties.toString()}\n")
}
}
report
}
//Get the detailed report
def getDetailedReport(projectResultHolder) {
def report = new StringBuffer()
report.append(drawLine()).append('\n')
report.append("\t\t\tTest Execution Detailed Report\n")
report.append(drawLine()).append('\n')
projectResultHolder.suiteResults.each { suite, details ->
report.append("Test Suite : ${suite}\n")
report.append("Result : ${getResult(details.status)}\n")
report.append("Total Cases : ${details.testCaseCount}\n")
report.append("Cases Passed : ${details.passedCasesCount}\n")
report.append("Cases Failed: ${details.failedCasesCount}\n")
report.append(getTestCaseReport(details.casaeResults))
report.append(drawLine()).append('\n')
report.append(drawLine()).append('\n')
}
report
}
//Save the contents to a file
def saveToFile(file, content) {
if (!file.parentFile.exists()) {
file.parentFile.mkdirs()
log.info "Directory did not exist, created"
}
file.write(content)
assert file.exists(), "${file.name} not created"
}
def holder = new ProjectResultsHolder(log: log)
holder.buildProjectResults(runner, project.name)
def finalReport = new StringBuffer()
finalReport.append(getSummaryReport(project, holder))
finalReport.append(getDetailedReport(holder))
def reportFile = new File(reportFileName)
saveToFile(reportFile, finalReport.toString())
And here is the generated output:

How to access Body param when MockFor HTTPBuilder

I am writing test that mocks HTTPBuilder. Here is method call that uses the HTTBuilder
def http = new HTTPBuilder('http://localhost:8010')
public registerUpdate(Long id, Long version){
try{
http.request(Method.POST, JSON){ req ->
body = [
version: version,
id: id
]
response.success = {resp, json ->
log.warn "cached object id: $id and version: $version; status code: " + resp.statusLine.statusCode
}
}
}catch(Exception e){
log.warn('Failure Initiate Connection with Node Driver: ' + e.message);
}
In the test, i ensure that proper method, contentType and the body parameter is set accordingly.
def "some test"(){
setup:
def httpBuildMock = new MockFor(HTTPBuilder.class)
httpBuildMock.demand.request{
met, type, body ->
assert met == Method.POST
assert type == ContentType.JSON
assert 10 == body.version
// def resp = body.call(null)
}
def mockService = httpBuildMock.proxyInstance()
service.http = mockService
when:
service.registerUpdate(1,2)
then:
httpBuildMock.verify mockService
In this test, the assertion for the body.version doesn't work. it gives 'missingPropertyException'. In debug mode, i can see that body parameter has properties 'id' and 'version' but still gives exception. How do i assert for 'body' parameter? Thank You
def "ensure params passed in correctly"(){
setup:
def httpBuildMock = new MockFor(HTTPBuilder.class)
def reqPar = []
def success
def requestDelegate = [
response: [:]
]
httpBuildMock.demand.request(1){
Method met, ContentType type, Closure b ->
b.delegate = requestDelegate
b.call()
reqPar << [method: met, type: type, id: b.body.id, ver: b.body.version ]
}
when:
httpBuildMock.use{
service.registerUpdate(id,ver)
}
then:
assert reqPar[0].method == Method.POST
assert reqPar[0].type == ContentType.JSON
assert reqPar.ver[0] == ver
assert reqPar.id[0] == id
}
For more, please, see my post Mock Httpbuilder and POST Requests in Grails

Resources