How to define a custom argument matcher with mockito in spec2?

2.7k Views Asked by At

I want to verify if the business logic passes the expected user object to dao, but I can't figure how to write an custom argument matcher for it.

"user" should {
    "be saved" in {
        val dao = new UserDao()
        dao.save(any[User]) returns mock[User]

        runMyBusinessLogic();

        val expectedUser = new User("Freewind", 123.23234)
        there was one(dao).save(mymatcher(expectedUser));
    }
 }

The User class:

case class User(name:String, random: Double)

Which contains a double field, that I need to do some special comparison for it.

The mymatcher is the matcher I want to define:

def mymatcher(expected: User) = ??? {
    // compare `name` and `random`
}

But I don't know how to do it in spec2, and can't find any useful documents. Any helps?

2

There are 2 best solutions below

0
On

For mockito matching I used Matchers.argThat

import org.mockito.Matchers
import org.mockito.Mockito.verify

verify(service).methodCall(Matchers.argThat({
  case CaseClass("const", arg2) =>
    arg2 == expected
  case _ => false
}))
2
On

I use beLike matcher. Like this:

one(daoMock).insert { beLike[MyEntity] { case t:Entity => {
  t.summary mustEqual "Summary"
  t.description mustEqual "Description"
}}}

Inside beLike matcher you could use ordinary value matchers.