SOAP UI中对比REST接口JSON响应数组与JDBC XML响应的方法
Got it, let's walk through how to verify that your REST API's JSON response matches the data from your JDBC source in SoapUI. Since you already have both the REST service and JDBC data source set up in the same test case, here's a straightforward, script-based approach to compare them:
Step 1: Add a Script Assertion to Your REST Test Step
Head to your REST test step, go to the Assertions tab, click the plus sign, and select Script Assertion. This is where we'll write the code to fetch, transform, and compare the two datasets.
Step 2: Parse the REST JSON Response
First, we'll convert the REST API's JSON response into a list of easy-to-compare maps:
// Grab and parse the REST response def restResponse = context.response def restData = new groovy.json.JsonSlurper().parseText(restResponse)
Step 3: Transform the JDBC XML Response to Match the JSON Structure
JDBC responses in SoapUI come as XML, so we need to convert it into the same format as the REST JSON. Replace "JDBC Test Step Name" with the actual name of your JDBC test step:
// Fetch the JDBC test step's XML response def jdbcTestStep = context.testCase.testSteps["JDBC Test Step Name"] def jdbcXmlResponse = jdbcTestStep.getPropertyValue("Response") // Parse the XML and map it to match the REST JSON structure def jdbcData = new XmlSlurper().parseText(jdbcXmlResponse).ResultSet.Row.collect { row -> [ id: row.id.text().toInteger(), // Convert to integer to match JSON's number type first_name: row.first_name.text(), last_name: row.last_name.text(), avatar: row.avatar.text() ] }
Step 4: Compare the Two Datasets
Now we can check if the data matches. Choose the option that fits your needs:
Exact Order Match
If the API returns items in the exact same order as the JDBC source:
assert restData == jdbcData : "Mismatch found! Expected JDBC data: ${jdbcData}, Actual REST response: ${restData}"
Unordered Match (Same Items, Any Order)
If order doesn't matter (common in APIs), convert both lists to sets of strings to compare:
def restDataSet = restData.collect { it.toString() } as Set def jdbcDataSet = jdbcData.collect { it.toString() } as Set assert restDataSet == jdbcDataSet : """ Mismatch found! Missing in REST response: ${jdbcDataSet - restDataSet} Extra in REST response: ${restDataSet - jdbcDataSet} """
Step 5: Handle Edge Cases
- Data Type Consistency: Make sure to convert fields like
idto the correct type (JSON returns numbers, XML returns strings by default). - Null Values: If your data has nulls, adjust the mapping to handle them (e.g.,
row.someField.text() ?: null). - Partial Validation: If you only need to check specific fields, modify the maps to include only those fields before comparing.
This script will fail the test if there's any mismatch between the REST API response and your JDBC data, giving you clear feedback on what's wrong.
内容的提问来源于stack exchange,提问作者Rakesh133

