How can I mock chained methods

1,732 views
Skip to first unread message

Sharuru Z

unread,
Jun 15, 2016, 12:03:01 PM6/15/16
to Spock Framework - User
Hi there, I am using Spock framework in my Java project and I have a question that document can not help :(

Here is the case:

In one of my validatorImpl, before returning, I do something with error message handler like this: 

context.buildConstraintViolationWithTemplate(msg).addPropertyNode(mstChkGroupCodeDocumentNo.clearingNo()).addConstraintViolation();

And absolutely, this method should be mocked when testing the main logic of validator.

I don't know how to mock this kind of chained methods calling with Spock.

Please help me, thank you.

Michael Kutz

unread,
Jun 16, 2016, 2:56:23 AM6/16/16
to Spock Framework - User
First you should definitly think about your class structure and try to avoid these massive chains.

Anyway if you cannot avoid it, you can use this syntax to ease the pain of it:

context = Mock() { buildConstraintViolationWithTemplate(msg) >> Mock(...) { addPropertyNode(mstChkGroupCodeDocumentNo.clearingNo()) >> Mock(...) { addConstraintViolation() >> ... }

You will need to put in some classes in there (where I put "...") since Spock will not be able to reflect the return type of the mocked methods.

--
You received this message because you are subscribed to the Google Groups "Spock Framework - User" group.
To unsubscribe from this group and stop receiving emails from it, send an email to spockframewor...@googlegroups.com.
To post to this group, send email to spockfr...@googlegroups.com.
Visit this group at https://groups.google.com/group/spockframework.
For more options, visit https://groups.google.com/d/optout.

Sharuru Z

unread,
Jun 17, 2016, 2:32:01 PM6/17/16
to Spock Framework - User
Problem solved.

Thank you for your advice on my class structure, I am working hard on it.

Have a nice day :)

在 2016年6月16日星期四 UTC+9下午3:56:23,Michael Kutz写道:
Reply all
Reply to author
Forward
0 new messages