Commutativity

If order operands do not matter, we say that the operation is commutative. The most trivial examples would be addition and multiplication. The property should be universal for both of these operations. In the following code, we're creating two properties, one for addition and one for multiplication, and checking that our assumption is correct by comparing results of computations with the changed order of operands:

scala> forAll((a: Int, b: Int) => a + b == b + a).check
+ OK, passed 100 tests.
scala> forAll((a: Int, b: Int) => a * b == b * a).check
+ OK, passed 100 tests.

For strings, the addition is defined as a concatenation but is not commutative in general:

scala> forAll((a: String, b: String) => a + b == b + a).check
! Falsified after 1 passed tests.
> ARG_0: "u0001"
> ARG_0_ORIGINAL
> ARG_1: "u0000"
> ARG_1_ORIGINAL:

In this example, we can also see how ScalaCheck generates random inputs and finds some minimal failing case. If at least one of the strings is empty, the property becomes commutative which can be demonstrated with the following modification of the previous test where b is assigned an empty string:

scala> forAll((a: String) => a + "" == "" + a).check
+ OK, passed 100 tests.

This is an example of a conditional test for string concatenation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.110.155