Skip to content

Instantly share code, notes, and snippets.

@hidenorigoto
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hidenorigoto/9938782 to your computer and use it in GitHub Desktop.
Save hidenorigoto/9938782 to your computer and use it in GitHub Desktop.
ScalaTest

ScalaTestでテストするときのメモ

build.sbt

libraryDependencies ++= Seq(
  "org.scalatest" % "scalatest_2.10" % "2.1.0" % "test",
  "org.scalacheck" %% "scalacheck" % "1.11.3" % "test"
)
build.sbtのライブラリ指定に使う``%``記号の意味が何か分かっていない。

ScalaTestはいくつかのスタイルで記述できるが、FreeSpecスタイルが構文ノイズが少なく良さそう。 データプロバイダーの機能は、ScalaCheckのTableとforAllを使う(このためにPropertyChecks traitをミックスインする)。

package jp.xnni.register1

import org.scalatest.FreeSpec
import org.scalatest.prop.PropertyChecks

class CapabilityQueueSpec extends FreeSpec with PropertyChecks {

  "能力付きキュー" - {
    "要素を追加できる" in {
      val count = 2

      val q = new CapabilityQueue{ capability = 5 }
      val e = new QueueElement(count)

      q.enqueue(e)

      assert(q.length == count)
    }

    "要素を取り出しできる" in {
      val data = Table(
        ("capability", "count", "after"),
        (2, 5, 3),
        (3, 3, 0),
        (4, 3, 0)
      )

      forAll(data) {
        (c: Int, count: Int, after: Int) =>
          val q = new CapabilityQueue{ capability = c }
          val e = new QueueElement(count)

          q.enqueue(e)
          q.dequeue()

          assert(q.length == after)
      }
    }
  }
}

モックについては現時点ではどのツールが最適なのか試行錯誤中。ScalaMockの構文は魅力だが、現在のバージョンでうまく動作させられなかった(このエラー)。Mockito等Javaのライブラリを素直に使う方が安心かもしれない。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment