Freewind
Freewind

Reputation: 198258

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

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?

Upvotes: 4

Views: 2951

Answers (2)

Andrey
Andrey

Reputation: 800

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
}))

Upvotes: 2

Mike G.
Mike G.

Reputation: 690

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.

Upvotes: 4

Related Questions