Can Spock Mock a Java constructor

邮差的信 提交于 2019-12-01 04:06:42
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 Constructors in the Spock Reference Documentation). However, a better solution is to decouple the implementation of the MyConfigurator class, 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.

You can use GroovySpy for mocking constructors in Spock

For example:

def 'my test'() {
 given: 
 def solrZkClient = GroovySpy(SolrZkClient.class,global: true);
 when:
    MyConfigurator.staticMethodName('hostName:2181')
 then:
    // assertions
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!