如何使用Mockito在Scala对象中模拟一个函数?

时间:2017-01-15 16:34:22

标签: scala mockito scalatest

我是Scala的新手。我试图使用Mockito模拟一个简单的Scala函数,但是我收到以下错误。我已经检查了互联网,但我无法找出错误。

object TempScalaService {
  def login(userName: String, password: String): Boolean = {
    if (userName.equals("root") && password.equals("admin123")) {
      return true
    }
    else return false
  }
}

我的测试课程在

之下
class TempScalaServiceTest extends FunSuite with MockitoSugar{

  test ("test login "){
    val service = mock[TempScalaService.type]
    when(service.login("user", "testuser")).thenReturn(true)
    //some implementation
  }
}

但是我收到以下错误:

Cannot mock/spy class     com.pearson.tellurium.analytics.aggregation.TempScalaService$
Mockito cannot mock/spy following:
- final classes
- anonymous classes
- primitive types
org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class    com.pearson.tellurium.analytics.aggregation.TempScalaService$
Mockito cannot mock/spy following:
- final classes
- anonymous classes
- primitive types
   at  org.scalatest.mock.MockitoSugar$class.mock(MockitoSugar.scala:74)
    at    com.pearson.tellurium.analytics.aggregation.TempScalaServiceTest.mock(Temp    ScalaServiceTest.scala:7)
at     com.pearson.tellurium.analytics.aggregation.TempScalaServiceTest$$anonfun$    1.apply$mcV$sp(TempScalaServiceTest.scala:10)
    at    com.pearson.tellurium.analytics.aggregation.TempScalaServiceTest$$anonfun$    1.apply(TempScalaServiceTest.scala:9)
    at     com.pearson.tellurium.analytics.aggregation.TempScalaServiceTest$$anonfun$    1.apply(TempScalaServiceTest.scala:9)
    at    org.scalatest.Transformer$$anonfun$apply$1.apply$mcV$sp(Transformer.scala:    22)
    at org.scalatest.OutcomeOf$class.outcomeOf(OutcomeOf.scala:85)

3 个答案:

答案 0 :(得分:8)

您可以在对象扩展的特征中定义方法。然后简单地模仿特征:

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]

答案 1 :(得分:6)

您无法模拟对象,尝试将代码移动到类中:

class TempScalaService() {
  def login(userName: String, password: String): Boolean = {
    if (userName.equals("root") && password.equals("admin123")) {
      return true
    }
    else return false
  }
}

并创建服务:

object TempScalaService {
   private val service = TempScalaService()

   def apply() = service
}

使用依赖注入框架会更好,但它现在可以使用。

现在,对于测试,请使用:

val service = mock[TempScalaService]
when(service.login("user", "testuser")).thenReturn(true)

答案 2 :(得分:-1)

您可以创建一个Scala伴侣对象:

  1. 为您的课程编写测试用例。
  2. 让该对象与外界进行互动。