如何使用Mockito在Scala对象中模拟函数? [英] How to mock a function within Scala object using Mockito?

查看:318
本文介绍了如何使用Mockito在Scala对象中模拟函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 error.

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)

推荐答案

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

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
  }
}

并创建服务:

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)

这篇关于如何使用Mockito在Scala对象中模拟函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆