Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock function returning AnyVal with Mockito in Scala / Specs2?

I would like to stub a function returning AnyVal using Mockito in Scala (Specs2 to be precise), but it doesn't seam to work:

import org.specs2.mutable._
import org.specs2.mock._

case class V(s: String) extends AnyVal

class A {
  def f: V = new V("Hello")
}

class Sample extends Specification with Mockito {
    "Mockito" should {
        "mock A" in {
            val a = mock[A]
            a.f returns new V("hoge")
            a.f match {
                case V("hoge") => success
                case _ => failure
            }
        }
    }
}

This fails with:

V cannot be returned by f()
f() should return String

I found kind of workaround (based on which I provided above snippet) using marker interface/trait: https://gist.github.com/mtgto/9251779

but this is not any solution for me, hence it changes returned type (because of mocking/test library issue).

Anyone has seen this before and knows how to stub such function?

like image 526
Michał Majcherski Avatar asked Jul 14 '14 19:07

Michał Majcherski


1 Answers

I found one way of stubbing this function - using original Mockito's doReturn with underlying AnyVal's type (String in this case) instead of AnyVal itself, so:

org.mockito.Mockito.doReturn("hoge").when(a).f

instead of:

a.f returns new V("hoge")
like image 64
Michał Majcherski Avatar answered Sep 20 '22 11:09

Michał Majcherski