Reputation: 22486
org.spockframework:spock-core:0.7-groovy-2.0
Gradle 1.12
Groovy 1.8.6
Hello,
I have a function that will return a JSON string. And I want to test that my function correctly creates the JSON format. However, I am having a problem with maybe some escape characters as the test always fails.
This is the correct JSON format I am expecting and testing against:
{"function":"verifyEmail","parameters":[{"email_pwd":"password","session_id":"S1234","snapz_id":"T1234","email":"[email protected]","access_token":"abcd"}]}
However, setting up the condition is proving difficult because of the double quotes
and the [ ]
characters. I have tried to escape them.
This is the function:
def 'Parse the string to create JSON object'() {
setup:
def requestFactory = new RequestFactory();
def snapzJSON = requestFactory.createWSRequest(FunctionReq.VERIFY_EMAIL, accessToken, sessionId, snapzId, email, emailPwd)
expect: 'Correctly formats JSON string'
System.out.println("SPOCK TEST: " + snapzJSON.createJSONRequest())
snapzJSON.createJSONRequest() == '{\"function\":\"verifyEmail\",\"parameters\":\\[{\"email_pwd\":\"password\",\"session_id\":\"S1234\",\"snapz_id\":\"T1234\",\"email\":\"[email protected]\",\"access_token\":\"abcd\"}\\]}'
}
And this is the result:
Condition not satisfied:
snapzJSON.createJSONRequest() == '{\"function\":\"verifyEmail\",\"parameters\":\\[{\"email_pwd\":\"password\",\"session_id\":\"S1234\",\"snapz_id\":\"T1234\",\"email\":\"[email protected]\",\"access_token\":\"abcd\"}\\]}'
| | |
| | false
| [parameters:[[session_id:S1234, snapz_id:T1234, email:[email protected], email_pwd:password, access_token:abcd]], function:verifyEmail]
abcd S1234 T1234 [email protected] password
Is there an easier way of doing this?
Many thanks for any suggestions,
Some additional output from test results:
jsonObject: {"parameters":[{"session_id":"S1234","snapz_id":"T1234","email":"[email protected]","email_pwd":"password","access_token":"abcd"}],"function":"verifyEmail"}
SPOCK TEST: [parameters:[[session_id:S1234, snapz_id:T1234, email:[email protected], email_pwd:password, access_token:abcd]], function:verifyEmail]
Upvotes: 2
Views: 3185
Reputation: 84786
In this line:
snapzJSON.createJSONRequest() == '{\"function\":\"verifyEmail\",\"parameters\":\\[{\"email_pwd\":\"password\",\"session_id\":\"S1234\",\"snapz_id\":\"T1234\",\"email\":\"[email protected]\",\"access_token\":\"abcd\"}\\]}'
You're comparing String
with Map
. You need to parse the JSON string on the right (using JsonSlurper
) and the compare the values. There's also no need to esacpe "
when single quote used '
.
You can also serialize left side (snapzJSON.createJSONRequest()
to string using JsonOutput
) and then compare.
It's much better to compare maps.
Upvotes: 3