User Guide - Argument matching

Argument matching

ScalaMock supports three types of generalised matching:

Wildcard values are specified with an * (asterisk). For example:

val mockedFunction = mockFunction[String, Object, Unit] // (String, Object) => Unit
mockedFunction expects ("foo", *)

will match any of the following:

mockedFunction("foo", 42)
mockedFunction("foo", 1.0)
mockedFunction("foo", null)

Epsilon matching

Epsilon matching is useful when dealing with floating point values. An epsilon match is specified with the ~ (tilde) operator:

mockedFunction expects (~42.0)

will match:


but will not match:


Predicate matching

More complicated argument matching can be implemented by using where to pass a predicate.

def where[Arg1](predicate: (Arg1) => Boolean)
def where[Arg1, Arg2](predicate: (Arg1, Arg2) => Boolean)
def where[Arg1, Arg2, Arg3](predicate: (Arg1, Arg2, Arg3) => Boolean)

Example 1

In this example we will use the following PlayerLeaderBoard interface.

case class Player(id: Long, name: String, emailAddress: String, country: String)

trait PlayerLeaderBoard {
    def addPointsForPlayer(player: Player, points: Int): Unit

Now imagine that we want to set an expectation that addPointsForPlayer is called with:

To achieve that in ScalaMock we can use where as follows:

(leaderBoardMock.addPointsForPlayer _) expects (where {
  (player: Player, points: Int) => == 789 && points == 100

Example 2

mockedFunction = mockFunction[Double, Double, Unit] // (Double, Double) => Unit
mockedFunction expects (where { _ < _ }) // expects that arg1 < arg2