How to mock a function inside a Scala object using Mockito?

I am really new to Scala. I tried to make fun of a simple Scala function using Mockito, but I get the following error. I checked the Internet, but I could not find out about the error.

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

And my test class is below

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

But I get the following error:

 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) 
+4
scala mockito scalatest
source share
2 answers

You cannot mock objects, try moving the 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 } } 

and create a service:

 object TempScalaService { private val service = TempScalaService() def apply() = service } 

This would be better with dependency injection infrastructure, but now it will work.

Now for the test use:

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

You can define a method in an attribute that extends your object. Then just mock the sign:

 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] 
+7
source share

All Articles