This is just Groovy, or stubbing chained method calls

This is just a quick note to self because I am prone to forget such things. This blog is my reminder right? I am writing down the things that may be of use later.

So, today I spent a few hours trying to write just one test. For this chained method call:

        FindIterable<Document> ops = oplogCollection.find(filter)
                .sort(new BsonDocument().append("$natural", new BsonInt32(1)))

We are writing tests in both Groovy and Java, but this one was in Groovy. I was trying to stub the invocation so that it would be used in all the chained calls. And I was failing.
First I tried to use this kind of stub:

        FindIterable<Document> stub = Stub(FluentIterable)
        stub.sort(_ as Bson) >> { Bson filter ->
            // do whatever
            return stub
        stub.batchSize(_ as int) >> { int size ->
            // do whatever
            return stub

So, I declared a stub and I returned it all the time. No luck! Only the first chained method was called.
Then I thought, what if we try to return this instead? Unfortunately, in this case this point to the instance of your test class and not your stub, which I promptly learned.

So, I turned to the best authority.
Google and StackOverflow.

In the end, this is how it worked:

        FindIterable<Document> batchResult = [
                batchSize: { int size ->
                    return tmResult
                }] as FindIterable<Document>

        FindIterable<Document> sortResult = [
                sort: { Bson sort ->
                    return batchResult
                }] as FindIterable<Document>

So, the principle is that you have to create another stub for a chained method call, and then they get chained.
I live and I learn.


About Maryna Cherniavska

I have productively spent 10+ years in IT industry, designing, developing, building and deploying desktop and web applications, designing database structures and otherwise proving that females have a place among software developers. And this is a good place.
This entry was posted in java, Programming and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s