org.spockframework:spock-core:0.7-groovy-2.0
Gradle 1.12
Groovy 1.8.6
您好,
我有一个返回JSON字符串的函数。我想测试我的函数是否正确创建了JSON格式。但是,我遇到了一些问题,因为测试总是失败。
这是我期待和测试的正确的JSON格式:
{"function":"verifyEmail","parameters":[{"email_pwd":"password","session_id":"S1234","snapz_id":"T1234","email":"a@hotmail.com","access_token":"abcd"}]}
但是,由于double quotes
和[ ]
字符,因此设置条件很困难。我试图逃避它们。
这是功能:
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\":\"a@hotmail.com\",\"access_token\":\"abcd\"}\\]}'
}
这就是结果:
Condition not satisfied:
snapzJSON.createJSONRequest() == '{\"function\":\"verifyEmail\",\"parameters\":\\[{\"email_pwd\":\"password\",\"session_id\":\"S1234\",\"snapz_id\":\"T1234\",\"email\":\"a@hotmail.com\",\"access_token\":\"abcd\"}\\]}'
| | |
| | false
| [parameters:[[session_id:S1234, snapz_id:T1234, email:a@hotmail.com, email_pwd:password, access_token:abcd]], function:verifyEmail]
abcd S1234 T1234 a@hotmail.com password
有更简单的方法吗?
非常感谢任何建议,
测试结果的一些额外输出:
jsonObject: {"parameters":[{"session_id":"S1234","snapz_id":"T1234","email":"a@hotmail.com","email_pwd":"password","access_token":"abcd"}],"function":"verifyEmail"}
SPOCK TEST: [parameters:[[session_id:S1234, snapz_id:T1234, email:a@hotmail.com, email_pwd:password, access_token:abcd]], function:verifyEmail]
答案 0 :(得分:3)
在这一行:
snapzJSON.createJSONRequest() == '{\"function\":\"verifyEmail\",\"parameters\":\\[{\"email_pwd\":\"password\",\"session_id\":\"S1234\",\"snapz_id\":\"T1234\",\"email\":\"a@hotmail.com\",\"access_token\":\"abcd\"}\\]}'
您正在将String
与Map
进行比较。您需要在右侧解析JSON字符串(使用JsonSlurper
)并比较值。当单引号使用"
时,也无需使用es '
。
您还可以使用snapzJSON.createJSONRequest()
将左侧(JsonOutput
)序列化为字符串,然后进行比较。
比较地图要好得多。