【问题标题】:Problems using the Spock wildcard in unit test with Gradle在 Gradle 的单元测试中使用 Spock 通配符的问题
【发布时间】:2021-04-08 17:00:30
【问题描述】:

我在 Eclipse 2021-03 (4.19.0) 中使用 Spock 2.0-M4-groovy-3.0 和 Groovy 3.0.7。在单元测试中,我尝试创建一个像这样的 Mock:

1 * mockGoogleCalendarClient.bookTimeSlot(_)

实际代码需要一个具有多个字段的对象。我不关心对象,所以我想使用通配符。

当它运行时我得到这个:

Test 没有定义或继承接口 groovy.lang.GroovyObject 的已解析方法“abstract java.lang.Object getProperty(java.lang.String)”的实现。

只有当我在测试中使用通配符时才会发生这种情况。我试图找出这个错误,但到目前为止我还没有。为了取得进展,我将所描述的方法添加到测试中,如下所示:

@Override
public Object getProperty(String value)
{
  return new Object()
}

现在测试运行,但似乎没有与通配符匹配。偶然我在该方法上设置了一个断点,以查看传递给它的内容(如果有的话),结果是“_”。就好像 Spock 在问价值应该是什么。

为什么测试首先会出现这个问题?

【问题讨论】:

  • 你能想出一个我们可以运行的例子来说明问题吗?
  • 请提供重现此问题的MCVE,否则我们无能为力。
  • 您没有显示足够的信息来确定问题所在,添加getProperty 方法绝对不是正确的做法。

标签: groovy spock


【解决方案1】:

https://github.com/jeffbrown/toronaga07spock 是一个工作示例。

build.gradle

plugins {
    id 'groovy'
}

repositories {
    jcenter()
}

dependencies {
    implementation 'org.codehaus.groovy:groovy-all:3.0.7'
    testImplementation 'org.spockframework:spock-core:2.0-M4-groovy-3.0'
}

test {
    useJUnitPlatform()
    testLogging {
        events "passed", "skipped", "failed"
    }
}

src/main/groovy/toronaga07spock/CalendarHelper.groovy

package toronaga07spock

class CalendarHelper {

    CalendarClient client

    void book(String message) {
        client.bookTimeSlot message
    }
}

src/main/groovy/toronaga07spock/CalendarClient.groovy

package toronaga07spock

interface CalendarClient {
    void bookTimeSlot(String s)
}

src/test/groovy/toronaga07spock/CalendarHelperSpec.groovy

package toronaga07spock


import spock.lang.Specification

class CalendarHelperSpec extends Specification {

    def "test a basic mock"() {
        given:
        def helper = new CalendarHelper()
        def mockGoogleCalendarClient = Mock(CalendarClient)
        helper.client = mockGoogleCalendarClient

        when:
        helper.book 'Some Booking Message'

        then:
        1 * mockGoogleCalendarClient.bookTimeSlot(_)
    }
}

【讨论】:

    猜你喜欢
    • 2014-06-21
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    • 2014-09-30
    • 1970-01-01
    • 2014-08-21
    相关资源
    最近更新 更多