我正在使用Spock和RestAssured对休息服务执行一些集成测试。我在使用hamcrest closeTo
匹配器检查双值时遇到问题:
class PlaceITSpec extends Specification {
def "Create a Place"() {
given:
def place = ['name' : 'Depot A',
'location': [
'latitude': 40d,
'longitude': -3d
]]
def request = given().accept(ContentType.JSON).contentType(ContentType.JSON).body(place)
when: "POST /places"
def response = request.with().post("http://localhost:8080/places")
then: "I get a the created place resource and 201 status code"
response.then().log().all()
.statusCode(201)
.body("name", equalTo(place['name']))
.body("location.longitude", is(closeTo(place['location']['longitude'], 0.000001d)))
.body("location.latitude", is(closeTo(place['location']['latitude'], 0.000001d)))
.body("_links.self", notNullValue())
.body("_links.place", notNullValue())
}
}
测试失败了:
java.lang.AssertionError: 1 expectation failed.
JSON path location.longitude doesn't match.
Expected: is a numeric value within <1.0E-6> of <-3.0>
Actual: -3.0
一切似乎都好。试图丢弃明显的错误我使用了错误值1.然而测试失败了:
java.lang.AssertionError: 1 expectation failed.
JSON path location.longitude doesn't match.
Expected: is a numeric value within <1.0> of <-3.0>
Actual: -3.0
我认为我做错了什么。任何人都遭遇同样的问题?
答案 0 :(得分:2)
最后通过RestAssured doc
找到了正确的答案必须将浮点数与Java&#34; float&#34;进行比较。原始
我将代码更新为:
class PlaceITSpec extends Specification {
def "Create a Place"() {
given:
def place = ['name' : 'Depot A',
'location': [
'latitude': 40f,
'longitude': -3f
]]
def request = given().accept(ContentType.JSON).contentType(ContentType.JSON).body(place)
when: "POST /places"
def response = request.with().post("http://localhost:8080/places")
then: "I get a the created place resource and 201 status code"
response.then().log().all()
.statusCode(201)
.body("name", equalTo(place['name']))
.body("location.longitude", equalTo(place['location']['longitude']))
.body("location.latitude", equalTo(place['location']['latitude']))
.body("_links.self", notNullValue())
.body("_links.place", notNullValue())
}
}
检查纬度和经度值现在是否具有f
后缀,以指示float
原语而不是double
原语。并且还将is(closeTo(data,error))
更改为equalTo(data)