出于测试目的,我需要重写“equals”方法:
def any = [equals: { true }] as String
any == 'should be true'
// false
有关问题的更多详细信息:
class EmployeeEndpointSpec extends RestSpecification {
void "test employee" () {
when:
get "/v1/employee", parameters
then:
expectedStatus.equals(response.statusCode)
expectedJson.equals(response.json)
where:
parameters << [
[:],
[id: 824633720833, style: "small"]
]
expectedStatus << [
HttpStatus.BAD_REQUEST,
HttpStatus.OK
]
expectedJson << [
[errorCode: "badRequest"],
[
id: 824633720833,
name: "Jimmy",
email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7cdcecacadee7c1c6ccc2cac6cecb89c4c8ca" rel="noreferrer noopener nofollow">[email protected]</a>",
dateCreated:"2015-01-01T01:01:00.000", // this value should be ignored
lastUpdated: "2015-01-01T01:01:00.000" // and this
]
]
}
}
lastUpdated
和 dateCreated
可能会及时更改,我需要
以某种方式忽略它们。
最佳答案
如果不需要比较提到的字段 - 删除它们:
class EmployeeEndpointSpec extends RestSpecification {
void "test employee" () {
when:
get "/v1/employee", parameters
then:
expectedStatus.equals(response.statusCode)
def json = response.json
json.remove('dateCreated')
json.remove('lastUpdated')
expectedJson.equals(response.json)
where:
parameters << [
[:],
[id: 824633720833, style: "small"]
]
expectedStatus << [
HttpStatus.BAD_REQUEST,
HttpStatus.OK
]
expectedJson << [
[errorCode: "badRequest"],
[
id: 824633720833,
name: "Jimmy",
email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="43292a2e2e3a03252228262e222a2f6d202c2e" rel="noreferrer noopener nofollow">[email protected]</a>",
dateCreated:"2015-01-01T01:01:00.000",
lastUpdated: "2015-01-01T01:01:00.000"
]
]
}
}
我还将测试负面和正面场景分开。
您还可以与测试键值分开测试keySet()
,而不是比较整个 map 。这就是我这样做的方式:
then:
def json = response.json
json.id == 824633720833
json.name == "Jimmy"
json.email == "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32585b5f5f4b72545359575f535b5e1c515d5f" rel="noreferrer noopener nofollow">[email protected]</a>"
json.dateCreated.matches('<PATTERN>')
json.lastUpdated.matches('<PATTERN>')
如果您不喜欢最后两行,可以将其替换为:
json.keySet().contains('lastUpdated', 'dateCreated')
关于java - 如何在 Groovy 中模拟 String.equals?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28042074/