What _ (underscore) means in Spock tests?
Asked Answered
F

2

8

In one of the Spock tests I see a strange condition in then block:

0 * someInstance._

What does it mean?

Fossilize answered 10/12, 2014 at 7:41 Comment(0)
E
14

_ is a wildcard, any object. See here to find how its exactly implemented and here for the docs. _ it's used for instance to check invocation of a method which argument does not matter, then it looks like:

1 * obj.method(1, _)

In this particular case it's checked if method method on instance obj was invoked exactly once with 1 as a first argument and anything as a second.

Exploration answered 10/12, 2014 at 7:59 Comment(7)
A friendlier link to Spock documentation explaining wildcards and cardinality (your specific case).Tuberculous
Thanks @GregorPetrin! I wanted to show to implementation, rather the usage, nevertheless it's very useful.Exploration
Well it's good to have both, right? Anyway Spock has docs in two places and the Google Code version looks rather unfriendly, so I figure it's always good to provide a link to the modern version..Tuberculous
Sure, that's why I added it to the answer. Thanks, once again!Exploration
Ah, didn't see that :)Tuberculous
OK but in my example _ is not as parameter in method but like a method. So from what I understand from the links and comments is that it checks that all methods of someInstance not to be executed?Fossilize
In this particular case a none interaction with any method invocation on someInstance is checked. In simple words. There was no interaction with someInstance object.Exploration
G
-1

EDIT: My answer does not address the operators problem and refers to an unrelated problem. Correct answer can be seen above


_ is often used to denote private content/variables in languages such as Groovy/Javascript that do now follow or provide visibility directives.

While you can still access them from outside of the class or instance the developer is trying to tell you that this variable is intended to be only used internally.

Gillmore answered 10/12, 2014 at 7:48 Comment(3)
Java and Groovy have visibility directives so underscored private variables are not required, furthermore a variable should have at least some text after the underscore to clarify what it means. In this case it is a Spock specific wildcard as the other answer correctly states.Tuberculous
You are right about the wildcard use of the underscore (well done providing the link, not easy to come by). Groovy used to ignore visibility directives for a long time, could you please provide me a link to documentation showing that this has been addressed?Gillmore
It hasn't been addressed. Groovy still treats visibility specifically. I don't know about a convention e.g. from python that was applied to groovy.Exploration

© 2022 - 2024 — McMap. All rights reserved.