How to best implement a Matcher for Function parameters

147 views
Skip to first unread message

Thomas Sant'ana

unread,
Jun 16, 2011, 10:58:12 PM6/16/11
to specs2...@googlegroups.com
Hi all,

I'm trying to use specs2 in a project that uses an operation with the following signature.

trait Alpha[S] {

    def action(s:S, f: S=>S)
}

I'd like to do something like this:

  case class Beta extends Mockito {
    def e1() = {
      val m = mock[Alpha[Int]]
      m.action(10, x => x + 2)
      there was one(m).action(be_==(10),FuncCall(10,12))
    }
  }


I create a version of a matcher like this:

  case class FuncCall[A, B](in: A, out: B) extends Matcher[Function1[A, B]] {
    def apply[S <: Function1[A, B]](t: Expectable[S]) = {
      val calculated = t.value(in)
      result(calculated == out, t.description + " evaluates to " + calculated, t.description + " does not evaluates to " + calculated, t)
    }
  }

I'm really not sure this is the correct way. It does seem to work, messages are not very nice, but I'm ok with that.

I this the proper way to make such a function matcher?
Would it make since to have these as part of specs.


Thomas

etorreborre

unread,
Jun 17, 2011, 1:01:26 AM6/17/11
to specs2...@googlegroups.com
Hi Thomas, 

You could try to use a "Matcher adapter" (look for "adapting the actual value"):

def functionCall[A, B](in: A, out: B) = be_==(out) ^^ { (f: Function1[A, B]) => f(in) }

That's really a neat idea. We could start to generalize it:

def functionCall[A, B, C](a: A, b: B, c: C) = be_==(c) ^^ { (f: Function2[A, B, C]) => f(a, b) }

and so on.

But I suspect that the next step will be you wanting to write:

there was one(m).action(be_==(10), functionCall(10, be_>(5)))

so we need:

def functionCall[A, B](in: A, out: Matcher[B]): Matcher[Function1[A, B]] = out ^^ { (f: Function1[A, B]) => f(in) }

and then:

def functionCall[A, B](in: A, out: B): Matcher[Function1[A, B]] = functionCall(in, be_==(out))

Please play a bit with that and tell me what works and what doesn't (there might be variance issues in the general case I suspect).

Eric.






Reply all
Reply to author
Forward
0 new messages