web-dev-qa-db-ja.com

Scalaオブジェクト内の関数をMockitoを使用してモックする方法は?

Scalaは初めてです。簡単なScala関数をMockitoを使用して模擬しようとしましたが、次のエラーが発生しました。インターネットを確認しましたが、エラーを見つけることができませんでした。

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)
9
Dilan

オブジェクトをモックすることはできません。コードをクラスに移動してみてください。

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)
6
LuisKarlos

オブジェクトが拡張するトレイトでメソッドを定義できます。次に、単に特性を模擬します。

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]
9
Dan Simon