Unable to create a Spy on a constructor in Spock

623 views Asked by At

The declaration I'm looking to create a spy on:

 Producer<String, String> producer = new KafkaProducer<String, String>(producerProps)

My attempts to create the spy failed:

 def spySvc = GroovySpy(service, global:true)
    2 * new service.createKafkaProducer() >> mockedProducer; // fail
    2 * new KafkaProducer(_) >> mockedProducer;   // fail
    2 * new KafkaProducer<String,String>(_) >> mockedProducer; //fail

But when I factor out the Producer creation into its own method createKafkaProducer() and create a spy on the method invocation like so , it works:

 2 * service.createKafkaProducer() >> mockedProducer; // success

Any ideas?

( I realize that the code should be refactored to use proper DI, then the problem is trivial and doesn't need a Spy )

1

There are 1 answers

0
JavaHead On

I think @rafaelim is correct , KafkaProducer is a statically compiled code and GroovySpies don't work on it .