Getting "Too few invocations" on unit test with spock
Asked Answered
G

1

9

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.

Gigigigli answered 4/3, 2015 at 23:33 Comment(0)
U
8

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");
    }
}
Underskirt answered 5/3, 2015 at 12:45 Comment(2)
Hello Opal, thanks for your response. Yes, I know that I can use Spy and it works just perfectly. I want to understand what is the logic that this code with real object doesn't work.Gigigigli
@AramAslanyan it won't work because you do need spock in the invocations at any level - to verify invocations you must use spies or mocks, this is how interaction testing works. You need to wrap a real object somehow with the tools provided. Is that clear?Underskirt

© 2022 - 2024 — McMap. All rights reserved.