Piotr Pradzynski
Piotr Pradzynski

Reputation: 4535

How to verify if method was called with set of specified elements in Spock?

I have a test in Spock:

def repository= Mock(Repository)

@Subject
def service = new Service(repository)

def "test"() {
  given:
  def results = [ /* does not matter */ ]

  def element = XYZ

  when:
  def found = service.findByElement(element)

  then:
  1 * repository.findByElements(_ as Set) >> results 
}

which is working properly. But I would like to verify if repository.findByElements method is taking one element set with our specific element. How to achieve this?

Neither this:

1 * repository.findByElements([element] as Set) >> results

nor this:

1 * repository.findByElements({ assert it == [element] as Set }) >> results

does not work.

Upvotes: 2

Views: 3966

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42174

You can use an argument constraint that expects a closure representing a predicate. It looks similar to your second use case - the only difference is that there is no assert keyword needed (predicate has to return a boolean value). Variable it holds the argument value that your mocked method retrieves while being called, so you can create a predicate based on passed value.

def repository= Mock(Repository)

@Subject
def service = new Service(repository)

def "test"() {
    given:
    def results = [ /* does not matter */ ]

    def element = new Element("XYZ")

    when:
    def found = service.findByElement(element)

    then:
    1 * repository.findByElements({ it == [element] as Set }) >> results
}

Upvotes: 4

Related Questions