concept FsCheck in category f#

appears as: FsCheck, FsCheck
Get Programming with F#: A guide for .NET developers

This is an excerpt from Manning's book Get Programming with F#: A guide for .NET developers.

41.2. Introducing FsCheck

That’s enough theory for now—let’s move on to the practical side. FsCheck is a property-testing library that’s effectively a port of Haskell’s QuickCheck library. FsCheck allows you to provide it with a parameterized function that performs business logic, and then test the result of that logic. FsCheck calls the test function many times, each time with slightly different input values. In some ways, this isn’t so different from NUnit or xUnit’s TestCase or Theories features, except here you don’t specify the data to test against; FsCheck does.

At times you might want to control up front the data generated by FsCheck. For instance, take your fictional FlipCase function and write one of the property tests for it.

Listing 41.2. A function to flip case of all letters with a single property test
oen System let flipCase (text:string) = text.ToCharArray() |> Array.map(fun c -> if Char.IsUpper c then Char.ToLower c else Char.ToUpper c) |> String [<Property>] let ``Always has same number of letters`` (input:string) = let output = input |> flipCase input.Length = output.Length

The problem with this is that this function is designed to work only with letters when no numbers or special characters are allowed, and no null values either. If you run this test now, there’s a good chance that it will fail, because FsCheck will pick random strings, including those with nonletters. You could make the flipCase function throw out such values, but in this case, you want the test to tell FsCheck to supply only valid data to the test; you need a way to tell FsCheck to generate strings with only letters.

41.2.1. Running tests with FsCheck

Before jumping into the thick of things with full-blown property-based tests, let’s start with a simple test that uses FsCheck so you can get a feel for the library itself.

Figure 41.5. Setting a breakpoint within a unit test that’s called by FsCheck
F# Deep Dives

This is an excerpt from Manning's book F# Deep Dives.

FsCheck is a random-testing library based on QuickCheck. You specify properties that functions or methods satisfy, and it tests whether the properties hold in a large number of randomly generated cases. When using FsCheck and fuzz testing in general, the key to successful testing is to find good properties that should hold (see the following sidebar).