Last active
January 28, 2016 02:48
-
-
Save atsuya046/b415a8f8e5ba7e554d72 to your computer and use it in GitHub Desktop.
ScalaCheckで独自のGeneratorを作る ref: http://qiita.com/atsuya046/items/2ab7505336a9f892bc47
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
libraryDependencies += "org.scalacheck" %% "scalacheck" % "1.12.5" % "test" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ sbt test | |
~ | |
[info] + MyClass.calc: OK, passed 100 tests. | |
[info] Passed: Total 1, Failed 0, Errors 0, Passed 1 | |
[success] Total time: 4 s, completed 2016/01/28 11:28:23 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
case class MyClass(number: Int, multiplier: Multiplier) { | |
def calc: Int = { | |
number * multiplier.number | |
} | |
} | |
case class Multiplier(number: Int) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.scalacheck.{Arbitrary, Gen, Prop, Properties} | |
object MyClassTest extends Properties("MyClass") { | |
// MultiplierのGenerator | |
// -1000 ~ 1000のnumberを持つMultiplierを生成します | |
val genMultiplier: Gen[Multiplier] = for { | |
number <- Gen.chooseNum(-1000, 1000) | |
} yield Multiplier(number) | |
// MyClassのGenerator | |
// -1000 ~ 1000のnumberとgenMultiplierで生成したMultiplierを持つMyClassを生成します | |
val genMyClass: Gen[MyClass] = for { | |
number <- Gen.chooseNum(-1000, 1000) | |
multiplier <- genMultiplier | |
} yield MyClass(number, multiplier) | |
// Prop.forAllでMyClassの乱数を呼び出す際にArbitraryを定義 | |
implicit val arbMyClass = Arbitrary {genMyClass} | |
// テストの実行 | |
// 100パターンのMyClassをランダムに生成してcalcの挙動を | |
property("calc") = Prop.forAll{(myClass: MyClass) => | |
myClass.calc == myClass.number * myClass.multiplier.number | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment