Data-driven test with mocking
Asked Answered
L

1

6

I have a method that receives a ContactForm object and a map with recipients. So I wrote the following spec that the correct recipient from the Map is returned, based on the inquiry of the form:

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 ...

Is there a data-driven way to do this? Unfortunately, not passing the form but the inquiry string itself is not an option right now, since this would require massive refactoring. I was just curious if it is possible with Spock to do this data-driven although the mock has to be changed before each test.

Liggins answered 17/9, 2014 at 12:48 Comment(0)
B
10

You can do this in the following way (not sure if this is what You're asking for):

@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"]
}
Baalbeer answered 17/9, 2014 at 12:56 Comment(1)
Yes, thank you very much! Did not know using this in the setup part is possible.Liggins

© 2022 - 2024 — McMap. All rights reserved.