How to mock a function within Scala object using Mockito?
You cannot mock objects, try to move your code to a class:
class TempScalaService() {
def login(userName: String, password: String): Boolean = {
if (userName.equals("root") && password.equals("admin123")) {
return true
}
else return false
}
}
and create a service:
object TempScalaService {
private val service = TempScalaService()
def apply() = service
}
This would be better with a dependency injection framework, but it will work for now.
Now, for the test, use:
val service = mock[TempScalaService]
when(service.login("user", "testuser")).thenReturn(true)
You can define the method in a trait which your object extends. Then simply mock the trait:
trait Login {
def login(userName: String, password: String): Boolean
}
object TempScalaService extends Login {
def login(userName: String, password: String): Boolean = {
if (userName.equals("root") && password.equals("admin123")) {
return true
}
else return false
}
}
//in your test
val service = mock[Login]