How to mock a function within Scala object using Mockito?

前端 未结 3 403
梦如初夏
梦如初夏 2020-12-19 02:42

I am really new to Scala. I tried to mock a simple Scala function using Mockito, but I get the following error. I have checked the internet but I was unable to find out the

相关标签:
3条回答
  • 2020-12-19 03:05

    You can create a Scala Companion Object:

    1. Write test cases for you class.
    2. Let that object do the external world interaction.
    0 讨论(0)
  • 2020-12-19 03:21

    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]
    
    0 讨论(0)
  • 2020-12-19 03:27

    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)
    
    0 讨论(0)
提交回复
热议问题