I am trying to mock a method that it is calling an external service, I simplified the problem to try understand the root problem, I see I can mock a method in a trait but I cannot use same method in other class that is extending the Trait. Why? and how can I fix the problem?
I want to mock the login method:
case class User(id: Int, name: String)
trait LoginService {
def login(name: String, password: String): Option[User] = Some(User(1, "anne"))
}
class OtherService extends LoginService {
def getId: Int = {
val getPassword="xx" // more stuff to test...
login("Anne", getPassword).get.id
}
}
If I am trying to mock it in my scala test + mockito:
class MySpec extends AnyWordSpec with Matchers with MockitoSugar {
"test3" in {
val service = mock[LoginService]
when(service.login("Anne", "xx")) thenReturn Some(User(222, "AA"))
val other = new OtherService()
other.getId should be(222)
}
"test2" in {
val service = mock[OtherService]
when(service.login("Anne", "xx")) thenReturn Some(User(222, "AA"))
val other=new OtherService()
other.getId should be(222)
}
"test1" in {
val service = mock[LoginService]
when(service.login("Anne", "xx")) thenReturn Some(User(222, "AA"))
service.login("Anne","xx").get.id should be(222)
}
}
Only test1 is working, but If I need to validate the method getId it fails. Why test2 and test3 are not simulating my mocked user with id 222??
Dependencies:
"org.scalatest" %% "scalatest" % "3.2.14" % Test,
"org.mockito" %% "mockito-scala-scalatest" % "1.17.12" % Test,