加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:44:29 所属栏目:安全 来源:网络整理
导读:我是 Scala的新手.我试图使用Mockito模拟一个简单的Scala函数,但是我收到以下错误.我检查了互联网,但我无法找出错误. object TempScalaService { def login(userName: String,password: String): Boolean = { if (userName.equals("root") password.equals("
我是 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)

解决方法

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

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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读