mocking methods which use ClassTag in scala using scalamock

大憨熊 提交于 2019-12-06 03:34:50

This is similar to: ScalaMock User Guide: Mocking methods with implicit params - there is an implicit ClassTag parameter, so you have to convince Scala compiler that find[T](id:Int)(m: ClassTag[T]) should be converted to MockFunction2

The following code works with ScalaMock 3.2:

package com.paulbutcher.test.mock

import org.scalamock.scalatest.MockFactory
import org.scalatest.{ FlatSpec, ShouldMatchers }

import scala.reflect.ClassTag
import scala.util.{ Failure, Try }

case class User(first: String, last: String, enabled: Boolean)

trait DataProviderComponent {
  def find[T: ClassTag](id: Int): Try[T]
  def update[T](data: T): Try[T]
}

class UserRepsitory(implicit provider: DataProviderComponent) {
  def userEnabled(id: Int): Boolean = {
    val user = provider.find[User](id)
    user.isSuccess && user.get.enabled
  }
}

class ClassTagTest extends FlatSpec with ShouldMatchers with MockFactory {
  behavior of "ScalaMock"

  it should "handle mocking methods with class tags" in {
    implicit val mockProvider: DataProviderComponent = mock[DataProviderComponent]
    (mockProvider.find[User](_: Int)(_: ClassTag[User])).expects(13, *).returns(Failure[User](new Exception("Failed!")))

    val repo = new UserRepsitory()
    repo.userEnabled(13) should be(false)
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!