toy
toy

Reputation: 12131

How to partial mock a function with function as an argument in Scala using Mockito

I'm trying to mock a function using when but I keep getting this error

 2 matchers expected, 1 recorded:
 -> at com.concrete.test.LuigiHistoryServiceTest.testHistory(LuigiHistoryServiceTest.scala:23)

 This exception may occur if matchers are combined with raw values:
     //incorrect:
     someMethod(anyObject(), "raw String");
 When using matchers, all arguments have to be provided by matchers.
 For example:
     //correct:
     someMethod(anyObject(), eq("String by matcher"));

And this is my test code

val service: LuigiHistoryService = spy(new LuigiHistoryService)
when(service.runQuery(Matchers.anyString(), Matchers.any[ResultSet => Seq[ExtendedTaskStatus]].apply))
  .thenReturn(Seq.empty)

This is the signature of the method

def runQuery[T](query: String, fn: ResultSet => T): Seq[T] = {/* */}

Upvotes: 0

Views: 359

Answers (1)

proximator
proximator

Reputation: 688

I have tried the following and it seems fine:

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{FunSuite, Matchers}
import org.mockito.Mockito._
import org.mockito.Matchers._


@RunWith(classOf[JUnitRunner])
class MyTest extends FunSuite with Matchers with MockitoSugar {

  case class ResultSet()
  case class ExtendedTaskStatus()
  class LuigiHistoryService {
    def runQuery[T](query: String, fn: ResultSet => T): Seq[T]  = List()
  }

  test("simple test"){

    val service: LuigiHistoryService = spy(new LuigiHistoryService)
    when(service.runQuery(anyString(), any[ResultSet => Seq[ExtendedTaskStatus]].apply))
      .thenReturn(Seq.empty)

    def fun(r: ResultSet) = List(ExtendedTaskStatus)
    service.runQuery("hi", fun)

    verify(service)
  }

}

Can you please update this code if it does not solve your issue?

Upvotes: 1

Related Questions