lundi 2 novembre 2015

How do you mock scala call-by name in Mockito

Im trying to mock scala call-by name method in mockito. But running into this error.

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"));

Any suggestion would be appreciated. Thanks!

Here is the sample code and test file: Here Im trying to mock createCommand function. and give a mock so I can verify that execute is called or not.

  package com.example

  class Command(key: String, func: => Long) {
    def execute(): Long = {
      println("Command.execute")
      println("key = " + key)
      println("func = " + func)
      func
    }

  }

  class CacheHelper {


    def createCommand(cacheKey: String, func: => Long): Command = {
      println("cacheKey = " + cacheKey)
      println("func = " + func)
      new Command(cacheKey, func)
      //    Mock this method
    }

    def getOrElse(cacheKey: String)(func: => Long): Long = {

      println("circuitBreakerEnabled = " + isCircuitBreakerEnabled)
      if (isCircuitBreakerEnabled) {
        val createCommand1: Command = createCommand(cacheKey, func)
        println("createCommand1 = " + createCommand1)
        createCommand1.execute()
      }
      else {
        util.Random.nextInt()
      }
    }

    def isCircuitBreakerEnabled: Boolean = {
      println("CacheHelper.isCircuitBreakerEnabled")
      false
    }
  }

  import com.example.{CacheHelper, Command}
  import org.mockito.Matchers._
  import org.mockito.Mockito._
  import org.scalatest.{Matchers, _}
  import org.scalatest.mock.MockitoSugar

  class ExampleSpec extends FlatSpec with Matchers with BeforeAndAfter with MockitoSugar {

    "it" should "call commands execute" in {
      val cacheHelper: CacheHelper = new CacheHelper
      val commandMock: Command = mock[Command]
      val spyCacheHelper = spy(cacheHelper)

      when(spyCacheHelper.isCircuitBreakerEnabled).thenReturn(true)
      when(spyCacheHelper.createCommand(any(), anyLong())).thenReturn(commandMock)

      val result: Long = spyCacheHelper.getOrElse("key")(1L)
      println("result = " + result)
      verify(commandMock).execute()

    }

  }

Aucun commentaire:

Enregistrer un commentaire