Dil*_*lan 8 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
}
}
Run Code Online (Sandbox Code Playgroud)
我的测试课程如下
class TempScalaServiceTest extends FunSuite with MockitoSugar{
test ("test login "){
val service = mock[TempScalaService.type]
when(service.login("user", "testuser")).thenReturn(true)
//some implementation
}
}
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
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)
Run Code Online (Sandbox Code Playgroud)
您可以在对象扩展的特征中定义方法.然后简单地模拟特征:
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]
Run Code Online (Sandbox Code Playgroud)
您无法模拟对象,尝试将代码移动到类:
class TempScalaService() {
def login(userName: String, password: String): Boolean = {
if (userName.equals("root") && password.equals("admin123")) {
return true
}
else return false
}
}
Run Code Online (Sandbox Code Playgroud)
并创建一个服务:
object TempScalaService {
private val service = TempScalaService()
def apply() = service
}
Run Code Online (Sandbox Code Playgroud)
使用依赖注入框架会更好,但它现在可以工作.
现在,为了测试,使用:
val service = mock[TempScalaService]
when(service.login("user", "testuser")).thenReturn(true)
Run Code Online (Sandbox Code Playgroud)