groovy Hamcrest Matchers.equalTo在Gstring与字符串比较时报告错误

apeeds0o  于 2022-11-01  发布在  其他
关注(0)|答案(1)|浏览(144)

我有一个包含一个值为GString的参数的列表。当我通过Hamcrest进行比较时,我得到String不是GString失败,即使作为字符串进行比较时内容匹配
在比较过程中,让Hamcrest将Gstring解析为string的正确方法是什么?一种解决方法是在我将实际的Gstring添加到列表中时,对它调用.toString(),但这并不理想

@Test
    def stackOverflow() {
        given:
        // values
        def v1 = '01'
        def v2 = '02'

        // a groovy string containing them
        def param = "${v1}:${v2}"

        // a matcher using a concrete string
        def matcher = Matchers.equalTo("01:02")

        when:
        // add actual into a list
        def mylist = [param]

        then:
        // check that actual Gstring matches expected String and fail
        that mylist, Matchers.hasItem(matcher)
    }

错误

ondition not satisfied:

that mylist, Matchers.hasItem(matcher)
|    |       |
|    [01:02] class org.hamcrest.Matchers
false

Expected: a collection containing "01:02"
     but: mismatches were: [was <01:02>]
qgelzfjb

qgelzfjb1#

在声明变量时,只需使用String而不是def

import static spock.util.matcher.HamcrestSupport.that
import static org.hamcrest.Matchers.*
import spock.lang.*

class ASpec extends Specification {
    def stackOverflow() {
        given:
        // values
        def v1 = '01'
        def v2 = '02'

        // a groovy string containing them
        String param = "${v1}:${v2}"

        // a matcher using a concrete string
        def matcher = equalTo("01:02")

        when:
        // add actual into a list
        def mylist = [param]

        then:
        // check that actual Gstring matches expected String and fail
        that mylist, hasItem(matcher)
    }
}

Groovy Web Console中试用
p.s. @Test不属于斯波克,应该删除。

相关问题