How do you check a mock was called with a Seq irrespective of order

521 Views Asked by At

I have a method, which has been mocked, and takes a Seq as a parameter.

I want to check the method was called with a Seq with the same contents, but irrespective of order.

eg something like:

myMethod(Seq(0,1)) wasCalled once

which passes if we called myMethod(Seq(1,0))

1

There are 1 best solutions below

0
On BEST ANSWER

Consider argThat matcher which enables specifying a predicate matcher

argThat((s: Seq[Int]) => s.sorted == Seq(0,1))

For example

import org.scalatest.{FlatSpec, Matchers}
import org.mockito.{ArgumentMatchersSugar, IdiomaticMockito}

trait Qux {
  def foo(s: Seq[Int]): Int
}

class ArgThatSpec extends FlatSpec with Matchers with IdiomaticMockito with ArgumentMatchersSugar {
  "ArgThat" should "match on a predicate" in {
    val qux = mock[Qux]
    qux.foo(argThat((s: Seq[Int]) => s.sorted == Seq(0,1))) answers (42)
    qux.foo((Seq(1,0))) shouldBe (42)
  }
}