How to mock a function within Scala object using Mockito?

泄露秘密 提交于 2019-11-29 10:48:51
LuisKarlos

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]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!