Code Examples for

ScalaCheck: The Definitive Guide

Return to chapter index

1 ScalaCheck: Property-based Testing

  • 1.1 Traditional versus property-based unit testing
  • 1.2 Benefits from property-based testing
  • 1.3 Conclusion
  • 1.1 Traditional versus property-based unit testing


    import junit.framework.TestCase; public class MathTest extends TestCase { public void testMax() { int z = Math.max(1,2) assertEquals(2, z) } }
    import junit.framework.TestCase; public class MathTest extends TestCase { public void testMax2() { int z = Math.max(1,0) assertEquals(1, z) } public void testMax3() { int z = Math.max(10,10) assertEquals(10, z) } public void testMax4() { int z = Math.max(-2,0) assertEquals(0, z) } }
    import org.scalacheck.Properties import org.scalacheck.Prop.forAll object MathProps extends Properties("Math") { property("max") = forAll { (x: Int, y: Int) => val z = java.lang.Math.max(x, y) (z == x || z == y) && (z >= x && z >= y) } }

    1.2 Benefits from property-based testing


    scala> p.check ! Falsified after 23 passed tests. > ARG_0: List("-1", "-1") > ARG_0_ORIGINAL: List("935472295", "1", "-1", "-1", "2147483647", "2113129492", "2147483647") scala> p.check ! Falsified after 3 passed tests. > ARG_0: List("1", "1") > ARG_0_ORIGINAL: List("0", "1", "1", "1", "2147483647")

    1.3 Conclusion

    For more information about ScalaCheck: The Definitive Guide, please visit:

    http://www.artima.com/shop/scalacheck

    and:

    http://booksites.artima.com/scalacheck

    Copyright © 2013-2014 Artima, Inc. All rights reserved.

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.