1

それを呼び出すメソッドのテストをしたいと思いerror()ます。

IntEmptyStack.topspecs2でテストしたいのは次のとおりです。

abstract class IntStack {
  def push(x: Int): IntStack = new IntNonEmptyStack(x, this)
  def isEmpty: Boolean
  def top: Int
  def pop: IntStack
}
class IntEmptyStack extends IntStack {
  def isEmpty = true
  def top = error("EmptyStack.top")
  def pop = error("EmptyStack.pop")
}

そして、これまでに書いた仕様は次のとおりです。

import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import org.specs2.mutable.Specification

@RunWith(classOf[JUnitRunner])
class IntStackSpec extends Specification {

  "IntEmptyStack" should {
    val s = new IntEmptyStack
    "be empty" in {
      s.isEmpty must equalTo(true)
    }
    "raise error when top called" in {
      s.top must throwA[RuntimeException]
    }
  }
}

エラーは 13 行目で発生します"raise error when top called" in {。エラー メッセージは次のとおりですvalue must is not a member of Nothings.topScala は、抽象クラスで定義されている Int ではなく、Nothing として推論すると思います。この場合、エラーなしでテストを作成するにはどうすればよいでしょうか?

この質問に対するコメント/修正をありがとう。

例の参照: 例による Scala

4

1 に答える 1

5

ここでの問題は、scala (および Java) では、サブクラスがオーバーライドされたメソッドのスーパークラスよりも具体的な型を返すことができることです。この場合、メソッドIntEmptyStack.topの return-type is (は型階層の最下部にあるためNothing、のサブタイプです。IntNothing

a must throwA[X]の型aNothing

IntEmptyStack次のように宣言を変更します。

def top: Int = error("EmptyStack.top")
def pop: Int = error("EmptyStack.pop")

または、もちろん、ロジックの正確性が型システムによって証明されているという事実を許可することもできます。つまり、空のスタックの一番上にある要素を取得することはできません。戻り値の型はNothing! テストは必要ありません。

于 2012-06-22T09:33:12.777 に答える