Argument matching
Note that this chapter is not related to scalamock 7 experimental API. There are no argument matchers.
ScalaMock supports three types of generalised matching:
- wildcards
- epsilon matching
- predicate matching
Wildcard values are specified with an *
(asterisk). For example:
val mockedFunction = mockFunction[String, Object, Unit] // (String, Object) => Unit
mockedFunction.expects("foo", *).returns(())
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).returns(())
will match:
mockedFunction(42.0)
mockedFunction(42.0001)
mockedFunction(41.9999)
but will not match:
mockedFunction(43.0)
mockedFunction(42.1)
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:
points
equal to 100 andplayer
who can have anyname
, anyemailAddress
and come from anycountry
as long itsid
is 789
To achieve that in ScalaMock we can use where
as follows:
leaderBoardMock.addPointsForPlayer.expects(where {
(player: Player, points: Int) => player.id == 789 && points == 100
}).returns(())
Example 2
mockedFunction = mockFunction[Double, Double, Unit] // (Double, Double) => Unit
mockedFunction.expects.(where { _ < _ }).returns(()) // expects that arg1 < arg2