如何使用Spoc在Groovy测试中测试嵌套列表对象的属性

时间:2019-04-08 14:35:45

标签: groovy collections spock

我正在编写一个常规测试。我的响应对象应该是这样的:

[ school: new School( 
id: "School1", 
name: "School1", 
courses: [ 
new Course(id: "Course1", name: "Course1"),
new Course(id: "Course2", name: "Course2")])]

以下是我的测试:

def "should update the name of the school and course as per their id"() {

given:

def request = requestObject

when:

def response = myService.update(requestObject)

then: "name of the school should be equal to its id"
result.collect {
        it.name == it.id
}.every { it }

and: "name of each course should be equal to its id"
//Need help

}

我想不出如何将测试中的“和”部分写成一个嵌套的集合。

2 个答案:

答案 0 :(得分:1)

我宁愿在此处使用Groovy power assert以获得不匹配情况下的描述性错误消息:

then: "name of the school should be equal to its id"
result.each {
    assert it.name == it.id
}

and: "name of each course should be equal to its id"
result*.courses*.each {
    assert it.name == it.id
}

*.the Groovy spread operator

但是,如果您想知道哪个学校的课程不匹配,那么在and:部分中,它会变得更加冗长

答案 1 :(得分:0)

我认为这可以断言:

result.every { it.courses.every { course => course.id == course.name }

在每所学校中,每门课程名称必须等于其课程ID。