May spock mock constructor java

An attempt to expand Spock's appeal at work and run into this issue. Actually trying to write Unit Tests for the Groovy class, but one that calls Java. The static method invokes a private constructor. The code looks like this:

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

"SolrZkClient" is a third-party library (Apache). Since he is trying to connect to ZooKeeper, I would like to make fun of it for this Unit Test (instead of doing it internally as part of a unit test).

My test falls into the constructor without difficulty, but I can not get past this ctor:

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

Is there any way to do this?

+8
java unit-testing groovy spock
source share
2 answers

Since the test class is written in Groovy, you can make fun of the constructor call through the global Groovy Mock / Stub / Spy (see Mocking Constructors in the Spock reference documentation ). However, the best solution is to disable the implementation of the MyConfigurator class to make it more verifiable. For example, you can add a second constructor and / or a static method that allows you to pass an instance of SolrZkClient (or the base interface, if any). Then you can easily transfer the layout.

+9
source share

You can use GroovySpy for mocking designers in Spock

For example:

 def 'my test'() { given: def solrZkClient = GroovySpy("",30000, 30000, new OnReconnect() { @Override public void command() { . . . } }); when: MyConfigurator.staticMethodName('hostName:2181') then: // assertions } 
0
source share

All Articles