数据驱动的测试与模拟

时间:2014-09-17 12:48:56

标签: unit-testing groovy spock data-driven-tests

我有一个接收ContactForm对象的方法和一个包含收件人的地图。所以我编写了以下规范,根据表格的查询返回地图中的正确收件人:

def "Correct recipients for first inquiry"() {
    setup:
    def form = Mock(ContactForm)
    form.getInquiry() >> "Subject 1"

    expect:
    sut.getRecipients(form, recipientsTestMap) == ["recipient1"]
}

def "Correct recipients for second inquiry"() {
    setup:
    def form = Mock(ContactForm)
    form.getInquiry() >> "Subject 2"

    expect:
    sut.getRecipients(form, recipientsTestMap) == ["recipient2"]
}

// and so on ...

有数据驱动方式吗?不幸的是,没有传递表单,但查询字符串本身现在不是一个选项,因为这将需要大量重构。我很好奇Spock是否有可能做这个数据驱动,虽然必须在每次测试之前更改模拟。

1 个答案:

答案 0 :(得分:8)

您可以通过以下方式执行此操作(不确定这是否是您所要求的):

@Unroll
def "Correct recipients for #inquiry inquiry"() {
    setup:
    def form = Mock(ContactForm)
    form.getInquiry() >> inquiry

    expect:
    sut.getRecipients(form, recipientsTestMap) == result

    where:
    inquiry     | result
    "Subject 1" | ["recipient1"]
    "Subject 2" | ["recipient2"]
}