Groovy: Stubbing With Spock

I have a github repo for working with RabbitMQ clients. I have not done much with it so far, just a few of the Java samples.

I worked a bit on a Spock test that stubs a message. I am still not completely clear on the difference between mocking and stubbing. With Spock, it seems like you use stubbing when you want your fake object to return a value from a method call, while mocking will check if that method is invoked. It is one of those things that I do not look at very often and then quickly forget.

So I will post this so I at least remember how to do it.

Here is the code in the sample that gets the message:

QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String( delivery.getBody() );
System.out.println(" [x] Received '" + message + "'");

Here is the code for the test:

def delivery = Stub( QueueingConsumer.Delivery )
def x = "ok".getBytes()
delivery.getBody() >> x
// setup:

when:
    println( "Here is delivery.getBody(): ${delivery.getBody()}" )
    def stringOutput = new String( delivery.getBody() )
    println( "Here is stringOutput: ${stringOutput}" )
then:
    // (1..5) * delivery.getBody()
    stringOutput == "ok"

I admit, it needs a bit of cleaning up.

One thing that took me so long was that I thought the method I was stubbing returned a String, when it returned an array of bytes. delivery.getBody() kept returning null because I had

delivery.getBody() >> "ok"

Perhaps I should start making gists when I figure things out.

 

Image from  Aurora Consurgens, a 15th century manuscript housed at Central Library of Zurich. Image from e-Codices. This image is assumed to be allowed under Fair Use.