【发布时间】:2017-05-30 12:42:15
【问题描述】:
我对 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)
【问题讨论】:
-
你不需要在 Scala 中为字符串使用
.equals()。试试看:"hi" == new String("hi")是真的。此外,if (condition) { return true } else return false可以缩短为return condition甚至condition。