Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple assignments in the where clause of a spock test?

Tags:

groovy

spock

I'm using the Spock framework for testing, and I have a question regarding multivaraible assignment in a where clause.

I have the following test case:

def "sending a message delegates to message sender"() {
  when:
    sendMessage(x,y)
  then:
    1 * messageSender.send(x,y)
  where:
    x << 1
    y << 2
}

I want to replace the multiple variable assignments in the where clause with a single assignment operation. I tried:

where:
  [x,y] << [1,2]

but got a MissingMethod exception. I assume this is because the expression [1,2] is treated as an array rather than a list.

Note that the following worked:

where:
  [x,y] << [1,2].combinations()

It seems that the combinations() method returns a List type, but despite that the following did not work:

where:
  [x,y] << [1,2].asList()

Using combinations() is counter-intuitive, so I am wondering if there is a simple, elegant way of initializing multiple variables in Spock.

edit: I am using spock version 0.7-groovy-2.0

like image 734
John Q Citizen Avatar asked Mar 03 '14 23:03

John Q Citizen


People also ask

What is Spock Lang specification?

lang. Specification class. A Spock specification can have instance fields, fixture methods, feature methods, and helper methods. We should prefer normal instance fields because they help us to isolate feature methods from each other.

What is @shared in groovy?

@Shared is a Spock feature that says to the reader that this variable is the same for all feature methods. It is an instruction specifically for the unit test and makes the unit test more clear for the reader. The same can be said for the main Spock blocks.

Why spock framework?

Spock is a testing and specification framework for Java and Groovy applications. What makes it stand out from the crowd is its beautiful and highly expressive specification language. Thanks to its JUnit runner, Spock is compatible with most IDEs, build tools, and continuous integration servers.

What is @unroll in groovy?

As you can see in below Spock Test example, @Unroll annotation are used in some features, By putting @Unroll annotation on the feature. it means an iteration is required on feature and on each iteration values given in where block get substituted by its value and leading hash sign ( # ), to refer to data variables.


1 Answers

Multiple assignment has to be done as mentioned below:

[x, y] << [[1,2]]

Here is a contrived example where test fails for one combination.

Multiple variable data pipes uses an example from SQL ResultSet which is pretty much similar to the above example.

like image 94
dmahapatro Avatar answered Sep 22 '22 18:09

dmahapatro