scala/scalatest
scalatest-3.2.3 의 property based test
wefree
2023. 1. 25. 19:54
문제
https://wefree.tistory.com/77 의 property based test 를 scalatest-3.2.3 버전을 이용해 작성해 보자.
코드
build.sbt 에 scalatest, scalacheck 라이브러리를 추가한다.
libraryDependencies ++= Seq(
"org.scalatest" %% "scalatest" % "3.2.3" % Test,
"org.scalatestplus" %% "scalatestplus-scalacheck" % "3.1.0.0-RC2" % Test
)
테스트를 작성한다.
import org.scalacheck.Gen
import org.scalatest.BeforeAndAfter
import org.scalatest.funsuite.AnyFunSuite
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
object Calculator {
def lastDigit(n: Int): Int = math.abs(n) % 10
def isDivisibleByFive(n: Int): Boolean = n % 5 == 0
}
class CalculatorTest extends AnyFunSuite with BeforeAndAfter with ScalaCheckPropertyChecks {
test("lastDigit table test") {
val table = Table(
("number", "lastDigit"), // First tuple defines column names
(0, 0),
(1, 1),
(-1, 1),
(12, 2),
(-12, 2),
(123, 3)
)
forAll(table)((number, last) => assert(Calculator.lastDigit(number) === last))
}
test("isDivisibleByFive property test") {
forAll { x: Int =>
whenever(x >= 0) {
val last = Calculator.lastDigit(x)
assert(Calculator.isDivisibleByFive(x) === (last == 0 || last == 5))
}
}
}
test("isDivisibleByFive Gen test") {
val numbers: Gen[Int] = Gen.choose(-1000, 1000).map(_ * 3)
forAll(numbers) { x: Int =>
val last = Calculator.lastDigit(x)
assert(Calculator.isDivisibleByFive(x) === (last == 0 || last == 5))
}
}
}