Spock 可以模拟 Java 构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21194523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:13:40  来源:igfitidea点击:

Can Spock Mock a Java constructor

javaunit-testinggroovyspock

提问by JoeG

Trying to broaden the appeal of Spock at work and run into this issue. Actually trying to write Unit Tests for a Groovy class, but one that calls out to Java. A static method calls a private constructor. The code looks like:

试图扩大 Spock 在工作中的吸引力并遇到了这个问题。实际上试图为 Groovy 类编写单元测试,但需要调用 Java。静态方法调用私有构造函数。代码如下:

private MyConfigurator(String zkConnectionString){
    solrZkClient = new SolrZkClient(zkConnectionString, 30000, 30000,
            new OnReconnect() {
                @Override
                public void command() { . . . }
            });
}

"SolrZkClient" is from third party (Apache) Java library. Since it tries to connect to ZooKeeper, I would like to mock that out for this Unit Test (rather than running one internally as part of the unit test).

“SolrZkClient”来自第三方(Apache)Java 库。由于它尝试连接到 ZooKeeper,我想为此单元测试模拟它(而不是在内部运行一个作为单元测试的一部分)。

My test gets to the constructor without difficulty, but I can't get past that ctor:

我的测试毫无困难地到达构造函数,但我无法通过那个构造函数:

def 'my test'() {
    when:
        MyConfigurator.staticMethodName('hostName:2181')
    then:
        // assertions
}

Is there anyway to do this?

有没有办法做到这一点?

采纳答案by Peter Niederwieser

Since the class under test is written in Groovy, you should be able to mock the constructor call by way of a global Groovy Mock/Stub/Spy (see Mocking Constructorsin the Spock Reference Documentation). However, a better solution is to decouple the implementation of the MyConfiguratorclass, in order to make it more testable. For example, you could add a second constructor and/or static method that allows to pass an instance of SolrZkClient(or a base interface, if there is one). Then you can easily pass in a mock.

由于被测类是用 Groovy 编写的,您应该能够通过全局 Groovy Mock/Stub/Spy 模拟构造函数调用(请参阅Spock 参考文档中的模拟构造函数)。但是,更好的解决方案是将类的实现解耦,以使其更具可测试性。例如,您可以添加第二个构造函数和/或静态方法,以允许传递(或基接口,如果有的话)的实例。然后你可以轻松地传递一个模拟。MyConfiguratorSolrZkClient

回答by Raghu K Nair

You can use GroovySpy for mocking constructors in Spock

您可以使用 GroovySpy 在 Spock 中模拟构造函数

For example:

例如:

def 'my test'() {
 given: 
 def solrZkClient = GroovySpy(SolrZkClient.class,global: true);
 when:
    MyConfigurator.staticMethodName('hostName:2181')
 then:
    // assertions
}

回答by Beckster

def anySubscriber = GroovySpy(RealSubscriber, global: true)

1 * new RealSubscriber("Fred")

put that into def setup(){ }block or inside of given:label block

将其放入 defsetup(){ }块或given:标签块内