2017-12-04 4 views
0

ステートフルなテストのためのScalacheck documentationには、ATMマシーンが使用例として挙げられています。それが機能するためには、コマンドにはパラメータ、例えばPINまたは出金金額が必要です。与えられた例では、クラスCounterのメソッドにはパラメータがありません。Scalacheck - コマンドへのパラメータの追加

今、私の質問は、私はscalachecksステートフルテストでは、このような方法をテストすることができる方法である:

class Counter { 
    private var n = 0 
    def inc(i: Int) = n += i 
    ... 
} 

コマンドのrunnextStateメソッドは、パラメータを提供していません。 Random.nextIntを追加するrunnextStateで値が異なるしまうので、仕事やテストが失敗しないでしょう。

case object Inc extends UnitCommand { 
    def run(sut: Sut): Unit = sut.inc(Random.nextInt) 

    def nextState(state: State): State = state + Random.nextInt 
    ... 
} 

Sutにパラメータを渡す方法はありますか?あなたはどのようにgenCommandから気づくことのよう

答えて

1

は、ScalaCheck Commandsは、実際に初期genInitialStateによって生成された状態とgenCommandによって生成された一連のコマンド間の直積のようなものがありません。したがって、コマンドの中には実際にパラメータが必要なものがある場合は、それらをオブジェクトからクラスに変換し、それらにGenを提供する必要があります。 (PINコードの場合のように)あなたのパラメータは単なる定数ではなく変数であれば、あなたはどちらかのハードコードする必要があること

/** A generator that, given the current abstract state, should produce 
    * a suitable Command instance. */ 
def genCommand(state: State): Gen[Command] = { 
    val incGen = for (v <- arbitrary[Int]) yield Inc(v) 
    val decGen = for (v <- arbitrary[Int]) yield Dec(v) 
    Gen.oneOf(incGen, decGen, Gen.oneOf(Get, Reset)) 
} 

// A UnitCommand is a command that doesn't produce a result 
case class Inc(dif: Int) extends UnitCommand { 
    def run(sut: Sut): Unit = sut.inc(dif) 

    def nextState(state: State): State = state + dif 

    // This command has no preconditions 
    def preCondition(state: State): Boolean = true 

    // This command should always succeed (never throw an exception) 
    def postCondition(state: State, success: Boolean): Prop = success 
} 

case class Dec(dif: Int) extends UnitCommand { 
    def run(sut: Sut): Unit = sut.dec(dif) 

    def nextState(state: State): State = state - dif 

    def preCondition(state: State): Boolean = true 

    def postCondition(state: State, success: Boolean): Prop = success 
} 

注:だから、あなたはこのようなものが必要になりますドキュメントからの例を変更しますそれらをコマンドで使用するか、オブジェクトではなく仕様クラス全体を作成し、それらのパラメータを外部から渡します。

+0

ありがとう、これは私が探していたソリューションのようです! – amuttsch

関連する問題