2017-01-15 9 views
4

私はScalaにとって本当に新しいです。私はMockitoを使って単純な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) 
+0

Scalaの文字列に '.equals()'を使う必要はありません。それを試してください: '' hi "==新しい文字列(" hi ")'は真です。また、 'if(condition){return true} else false false'を' return condition'や 'condition'だけに短縮することができます。 –

答えて

5

を:

サービスを作成します。

これは依存性注入フレームワークでは優れていますが、今のところうまくいくでしょう。

さて、テストのために、使用:

val service = mock[TempScalaService] 
when(service.login("user", "testuser")).thenReturn(true) 
7

は、あなたのオブジェクトが伸びる特性でメソッドを定義することができます。

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] 
関連する問題