3

I want to mock this method

def zadd[V: ByteStringSerializer](key: String, scoreMembers: (Double, V)*): Future[Long] 

Tried this

mock.zadd(anyString(), Seq((anyDouble(), any String()), (anyDouble(), anyString())): _*) 

doesnt work because mockito says 3 matchers expected, but got 5 instead.

so I try using How to properly match varargs in Mockito

but, I cant even use the code listed in that example ArgumentMatchers.<String>any() gets flagged as error in my IDE saying not recognized type String

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
Abdul R
  • 43
  • 3
  • Based on this link (http://blog.siddhuw.info/matching-functions-as-arguments-and-varags-using-mockito-and-scala/) you'll have to use `argThat` and implement an ArgumentMatcher of your own. An alternate solution might be to switch to using `mockito-scala` instead. – second Aug 03 '19 at 12:44

1 Answers1

2

mockito-scala supports varargs out-of-the-box, for example

import cats.implicits._
import org.mockito.ArgumentMatchersSugar
import org.mockito.cats.IdiomaticMockitoCats
import org.mockito.scalatest.IdiomaticMockito
import org.scalatest._
import org.scalatest.concurrent.ScalaFutures
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

trait Foo {
  def zadd(key: String, scoreMembers: (Double, String)*): Future[Long]
}

class HelloSpec extends FlatSpec
    with Matchers
    with IdiomaticMockito
    with IdiomaticMockitoCats
    with ScalaFutures
    with ArgumentMatchersSugar {

  "Foo" should "mock varargs" in {
    val foo = mock[Foo]
    foo.zadd("", *) returnsF 42L
    foo.zadd("bar", (7.7, "qux")) returnsF 89L

    foo.zadd("", (1.1, "")).futureValue should be (42L)
    foo.zadd("bar", (7.7d, "qux")).futureValue should be (89L)
  }
}

where

libraryDependencies ++= Seq(
  "org.scalatest" %% "scalatest" % "3.0.8",
  "org.mockito" %% "mockito-scala" % "1.5.13",
  "org.mockito" %% "mockito-scala-scalatest" % "1.5.13",
  "org.mockito" %% "mockito-scala-cats" % "1.5.13",
  "org.typelevel" %% "cats-core"   % "2.0.0-M4"
)
Mario Galic
  • 47,285
  • 6
  • 56
  • 98