【问题标题】:Getting "Too few invocations" on unit test with spock使用 spock 在单元测试中获得“调用太少”
【发布时间】:2015-05-06 04:38:58
【问题描述】:

为简单起见,让我们举一个非常简单的类:

public class TestingClass {

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

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

现在我正在编写一个简单的测试,它检查当我们调用 method1() 时,method2() 是否被调用:

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

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

通过执行此测试,我收到以下错误:

运行方式一 运行方式二

调用太少:

1 * tesingClass.method2()(0 次调用)

为什么我会收到此错误?打印的日志显示method2() 被调用。

【问题讨论】:

    标签: spock


    【解决方案1】:

    在真实对象上测试交互时需要使用Spy,见下文:

    @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");
        }
    }
    

    【讨论】:

    • 您好 Opal,感谢您的回复。是的,我知道我可以使用 Spy 并且它工作得非常完美。我想了解这个带有真实对象的代码不起作用的逻辑是什么。
    • @AramAslanyan 它不起作用,因为您确实需要在任何级别的调用中使用 spock - 要验证调用,您必须使用间谍或模拟,这就是交互测试的工作方式。您需要使用提供的工具以某种方式包装真实对象。清楚吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    相关资源
    最近更新 更多