Search code examples
spock

Getting "Too few invocations" on unit test with spock


For simplicity let's take a very simple class:

public class TestingClass {

    public void method1(){
        System.out.println("Running method 1");
        method2();
    }

    public void method2(){
        System.out.println("Running method 2");
    }
}

Now I'm writing a simple test, which checking that when we invoke method1(), method2() is invoked:

class TestingClassSpec extends Specification {
    void "method2() is invoked by method1()"() {
        given:
        def tesingClass = new TestingClass()

        when:
        tesingClass.method1()
        then:
        1 * tesingClass.method2()
    }
}

by executing this test, I'm getting the following error:

Running method 1 Running method 2

Too few invocations for:

1 * tesingClass.method2() (0 invocations)

Why I'm getting this error? Printed log is show that method2() was invoked.


Solution

  • You need to use Spy when testing interactions on real objects, see below:

    @Grab('org.spockframework:spock-core:0.7-groovy-2.0')
    @Grab('cglib:cglib-nodep:3.1')
    
    import spock.lang.*
    
    class TestingClassSpec extends Specification {
        void "method2() is invoked by method1()"() {
            given:
            TestingClass tesingClass = Spy()
    
            when:
            tesingClass.method1()
    
            then:
            1 * tesingClass.method2()
        }
    }
    
    public class TestingClass {
    
        public void method1(){
            System.out.println("Running method 1");
            method2();
        }
    
        public void method2(){
            System.out.println("Running method 2");
        }
    }