Getting "Too few calls" on unit test with spock

For simplicity, we 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 am writing a simple test that checks that when method1 () is called, method2 () is called:

 class TestingClassSpec extends Specification { void "method2() is invoked by method1()"() { given: def tesingClass = new TestingClass() when: tesingClass.method1() then: 1 * tesingClass.method2() } } 

by running this test, I get the following error:

Execution Method 1 Execution Method 2

Too few calls to:

1 * tesingClass.method2 () (0 invocations)

Why am I getting this error? The print journal shows that method2 () was called.

+5
source share
1 answer

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"); } } 
+3
source

Source: https://habr.com/ru/post/1214701/


All Articles