2016-06-30 4 views
0

可能であれば、模擬宣言を再利用したいと思います。 ここにはScalaTestとMockitoを使用した最小の非実例があります。私ははい最初のテストの値を期待していますが、私は値を取得します。テスト間で模擬宣言を再利用

最新のMockito.whenがすべてのテスト条項に適用されたようです。

in節に疑似命令を宣言しないようにする方法はありますか?私にはわからない

import org.mockito.Mockito._ 
import org.scalatest.mock.MockitoSugar 
import org.scalatest.{Matchers, WordSpec} 

class ReuseMocksSpec extends WordSpec with Matchers with MockitoSugar { 

    "A test" when { 
    "sharing mocks among tests" should { 
     "get yes value" in { 
     val value = withValue("yes") { service => 
      service.getVal 
     } 
     value should be("yes") 
     } 
    } 
    "sharing mocks among other tests" should { 
     "get other value" in { 
     val value = withValue("other") { service => 
      service.getVal 
     } 
     value should be("other") 
     } 
    } 
    } 

    def withValue(value: String)(body: (Service => String)) = { 
    val service = mock[Service] 
    when(service.getVal).thenReturn(value) 
    body(service) 
    } 

    trait Service { 
    def getVal: String 
    } 
} 

import org.mockito.Mockito._ 
import org.scalatest.mock.MockitoSugar 
import org.scalatest.{Matchers, WordSpec} 
​ 
class ReuseMocksSpec extends WordSpec with Matchers with MockitoSugar { 

    "A test" when { 
    val service = mock[Service] 
    "sharing mocks among tests" should { 
     when(service.getVal).thenReturn("yes") 
     "get yes value" in { 
     service.getVal should be("yes") 
     } 
    } 
    "sharing mocks among other tests" should { 
     when(service.getVal).thenReturn("other") 
     "get other value" in { 
     service.getVal should be("other") 
     } 
    } 
    } 
​ 
    trait Service { 
    def getVal: String 
    } 
} 

答えて

0

私はそれを設計し仕方を見直し、今、私のモックを構築する機能を使用しています:

def withValue(value: String)(body: (Service => String)) = { 
    val service = mock[Service] 
    when(service.getVal).thenReturn(value) 
    body(service) 
} 

テストクラスになるでしょうもしそれを行う最もクリーンで簡単な方法ですが、それは動作します...

関連する問題