My first question, question, was answered but it uncovered another issue I am having. Here is the scenario.
Example code (expanded from previous question)
A Model:
case class User (first: String, last: String, enabled: Boolean)
Component Definition:
trait DataProviderComponent {
def find[T: ClassTag](id: Int): Try[T]
def update[T](data: T): Try[T]
}
One of the concrete component implementations (updated implementation):
class DbProvider extends DataProviderComponent {
override def find[T: ClassTag](id: Int): Try[T] = {
Try {
val gson = new Gson()
val testJson = """{"first": "doe", "last": "jane", "enabled": false}"""
gson.fromJson(testJson, implicitly[ClassTag[T]].runtimeClass).asInstanceOf[T]
}
}
override def update[T](data: T): Try[T] = ???
}
Implicit usage of component impl somewhere in system:
implicit val provider = new DbProvider()
class UserRepsitory(implicit provider: DataProviderComponent) {
def userEnabled(id: Int): Boolean = {
val user = provider.find[User](id)
user.isSuccess && user.get.enabled
}
}
Unit Test1, trying to mock out provider in order to isolate repository test. This does not work, the following execption is thrown when test is run. I expect it is because of ClassTag usage because when I create another sample which does not use ClassTag, it works fine.
org.scalamock.MockFunction2 cannot be cast to org.scalamock.MockFunction1 java.lang.ClassCastException: org.scalamock.MockFunction2 cannot be cast to org.scalamock.MockFunction1
class UserRepository$Test1 extends FunSuite with Matchers with MockFactory {
test("invalid data request should return false") {
implicit val mockProvider: DataProviderComponent = mock[DataProviderComponent]
(mockProvider.find[User] _).expects(13).returns(Failure[User](new Exception("Failed!")))
val repo = new UserRepsitory()
repo.userEnabled(13) should be (false)
}
}
Unit Test2 does work but is hard to maintain and requires more code:
class UserRepository$Test2 extends FunSuite with Matchers with MockFactory {
test("invalid data request should return false") {
class FakeProvider extends DataProviderComponent {
override def find[T:ClassTag](id: Int): Try[T] = Failure[T](new Exception("Failed!"))
override def update[T](data: T): Try[T] = ???
}
implicit val provider = new FakeProvider()
val repo = new UserRepsitory()
repo.userEnabled(13) should be (false)
}
}
Unit Test3 does work but - used just to test ClassTag implemenation:
class UserRepository$Test3 extends FunSuite with Matchers with MockFactory {
test("prove sut works") {
implicit val provider = new DbProvider()
val repo = new UserRepsitory()
val user = repo.userEnabled(13)
println(user.toString)
}
}
Am I using ClassTag wrong or is the mock not able to properly mock it?