ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • scalatest-3.0.5 의 property based test
    scala/scalatest 2021. 11. 14. 18:45

    문제

    정수 n 에 대해

    • n 의 마지막 자리수를 구하는 함수
    • n 이 5 의 배수인지를 체크하는 함수를 구현했다.
    object Calculator {
      def lastDigit(n: Int): Int = math.abs(n) % 10
      def isDivisibleByFive(n: Int): Boolean = n % 5 == 0
    }

    잘 구현되었는지 체크를 위해  scalatest property based test 를 작성하자

    특히, n 이 5의 배수일 경우 n 의 마지막 자리수가 0 또는 5 임을 체크하도록 하자.

     

    코드

    build.sbt 에 scalatest, scalacheck 라이브러리를 추가한다.

    libraryDependencies ++= Seq(
      "org.scalatest"  %% "scalatest"  % "3.0.5"  % "test",
      "org.scalacheck" %% "scalacheck" % "1.13.5" % "test"
    )

     

    테스트를 작성한다.

    import org.scalacheck.Gen
    import org.scalatest.prop.PropertyChecks
    import org.scalatest.{BeforeAndAfter, FunSuite}
    
    class CalculatorTest extends FunSuite with BeforeAndAfter with PropertyChecks {
      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))
        }
      }
    }

     

    'scala > scalatest' 카테고리의 다른 글

    BeforeAndAfterAll  (0) 2023.03.21
    BeforeAndAfter  (0) 2023.03.21
    scalatest-3.2.3 의 property based test  (0) 2023.01.25
    scalatest-3.0.5 에서 scalacheck 의 generator 사용하기  (0) 2022.02.19

    댓글

Designed by Tistory.