私は特定の値を提供するために、モック設定を作成し、Scalaでテストを設定します。私はScalaTest 3.0.1、3.4.2 ScalaMock、 および型保証1.3.1を使用しています。目標は、テストを実行する前にconfigの値を疑似化することです。 http://www.scalatest.org/user_guide/testing_with_mock_objectsとhttp://scalamock.org/user-guide/features/のドキュメントは カップルのオプションを提供するように見えます。まず、ここではいくつかのターゲット・コードは次のとおりです。反復メソッド呼び出しのためにScalaMockを一度セットアップするには?
import com.typesafe.config.Config
class Sample(config: Config) {
private val aValue = config.getDouble("aValue")
}
1時間まで、すべてを設定するか、各テストの前にすべてのものを設定することが可能なはずであるように思え。この試みは失敗します。
class SampleSpec extends FlatSpec with MockFactory with BeforeAndAfterAll {
private val mockConfig = mock[Config]
override def beforeAll {
(mockConfig.getDouble _).expects("aValue").returning(1.0).anyNumberOfTimes()
}
"testOne" should "return 1" in {
new Sample(mockConfig)
}
"testTwo" should "return 1" in {
new Sample(mockConfig)
}
}
最初のテストが成功したが、治具における第二のテストは失敗し、このエラーが生成されます
Unexpected call: <mock-1> Config.getDouble(aValue)
Expected:
inAnyOrder {
}
Actual:
<mock-1> Config.getDouble(aValue)
ScalaTestFailureLocation: scala.Option at (Option.scala:120)
org.scalatest.exceptions.TestFailedException: Unexpected call: <mock-1> Config.getDouble(aValue)
Expected:
inAnyOrder {
}
はここで別のアプローチです:
class SampleSpec extends FlatSpec with MockFactory with BeforeAndAfter {
private val mockConfig = mock[Config]
before {
(mockConfig.getDouble _).expects("aValue").returning(1.0)
}
"testOne" should "return 1" in {
new Sample(mockConfig)
}
"testTwo" should "return 1" in {
new Sample(mockConfig)
}
}
それが生成しますこの例外:
An exception or error caused a run to abort: assertion failed: Null expectation context - missing withExpectations?
java.lang.AssertionError: assertion failed: Null expectation context - missing withExpectations?
最初の試行はなぜ失敗するのですか?テストはgetDouble
は何度でも呼び出すことができるように指定し、まだanyNumberOfTimes()
が使用されていなかったかのように、第2 テストは失敗します。メソッドを一度嘲笑して、 が繰り返し呼び出されるように、これをどのようにコード化すればよいですか? 2回目の試行はなぜ失敗するのですか?モックをリセットして再利用できる方法はありますか?
私は最初の手法(OneInstancePerTest)を適用しました。私は他の場所でこれについてドキュメントを見てきましたが、この説明はより明確です。例を提供するための編集... –