0

Let's say my class is Foo with a recursive method bar which calls a service like below

public class Foo
{
    private DataService service;

    public void perform(int count, final SomeObject obj)
    {
        if(count > 0)
        {
            service.refresh(obj);
            count = count- 1;
            perform(count, obj)
        }
    }

}

Now I want to verify number of times refresh method gets called for differnt input, something like this

@Test
def "test method"()
{
given:
def obj = Mock(SomeObject)

expect:
foo.perform(refreshRequests, inputObj)

where:
refreshRequests | inputObj | 
1               | obj      | 1 * service.refresh(obj)
2               | obj      | 2 * service.refresh(obj)
}

Is there a way to achieve something like this? Thanks in advance!

Leonard Brünings
  • 12,408
  • 1
  • 46
  • 66
Rupesh Vislawath
  • 125
  • 1
  • 11

1 Answers1

2

You were close, this is how you do it. You basically just move the interaction to the then block where it belongs, and use the refreshRequests as expected invocation count.

refreshRequests * service.refresh(inputObj)

The full runnable example with some minor modifications.

public class Foo
{
    private DataService service;

    public void perform(int count, String obj)
    {
        if(count > 0)
        {
            service.refresh(obj);
            count = count- 1;
            perform(count, obj)
        }
    }
}

interface DataService {
    void refresh(String aString)
}

class ASpec extends spock.lang.Specification {

    def "test method"()    {
        given:
        def service = Mock(DataService)
        Foo foo = new Foo(service: service)

        when:
        foo.perform(refreshRequests, inputObj)

        then:
        refreshRequests * service.refresh(inputObj)

        where:
        refreshRequests | inputObj 
        1               | "a" 
        2               | "b"     
    }
}

Try it in the groovy web console.

Leonard Brünings
  • 12,408
  • 1
  • 46
  • 66