FsCheck: An introduction
Tags: fsharp, fscheck, testing
Published: 2020-06-30 17:45:08

---
title: FsCheck: An introduction
published: true
date: 2020-06-30 08:00:00 UTC
tags: fsharp,FsCheck,Testing
canonical_url: https://SimonReynolds.ie/fscheck-an-introduction/
---

 ![FsCheck: An introduction](https://images.unsplash.com/photo-1536875489903-655d152ed785?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ)

We've all heard of unit testing and some of us have even been known to practice it. It has a simple premise

- Have a method or some other "unit" of code you want to test
- Pass in some contrived test data
- Compare the result to what you would expect it to be

This is essentially _example based testing_. All we can guarantee with it is that the output is as expected for the given input. That may be a single case or a handful of test cases.

If we were to imagine we had a requirement for a method that would reverse any given string of text then we could have a particularly obtuse developer who only wants to implement exactly what is in the requirement, no more and no less.

If the requirement states

> _For example, a given string "abcdef" would be reversed to "fedcba"..._

then it's possible that our developer may write something like this.

<!--kg-card-begin: markdown-->
```fsharp
test "String reverses correctly" {
    let expected = "fedcba"
    let input = "abcdef"
    
    Expect.equal (reverse input) expected "Should be equal"
}
```
<!--kg-card-end: markdown-->

This all looks straightforward enough until we look at the implementation of `reverse`

<!--kg-card-begin: markdown-->
```fsharp
let reverse (input:string) =
    "fdecba"
```
<!--kg-card-end: markdown-->

This is clearly a contrived example but we can see how one test is not exhaustive. But what's the alternative? We clearly can't create a list of every possible string of text. Especially when we consider the amount of whitespace and non-printable characters.

We need random input, this is where we need _property based testing_. We can consider the properties of a method that would reverse a string.

- The characters that make up the original string will all be in the reversed string, but in the opposite order
- So if we count each character in both, we should never have a character that only appears once
- Both strings should be the same length
- If we join the two strings into a new string, the same character should be repeated in the middle
- Reversing a string twice should give us the original again

Reversing the string again is a useful test but by itself does not prove that the `reverse` method is complete. After all if it just returned the string unchanged then the string would be the same after two calls to `reverse`.

A more useful test would be to compare the reversed string and iterate backwards through each character. Each character should match if we were to iterate forwards through the original string.

Let's use a property based testing framework called [FsCheck](https://fscheck.github.io/FsCheck/index.html). It allows us to test the assumptions in our methods and find edge cases we never even considered.

<!--kg-card-begin: markdown-->
```fsharp
let reverse (input:string) =
    if isNull input then
        null
    else
        let charArray = input.ToCharArray() |> Seq.rev |> Seq.toArray
        String(charArray)

let properties =
    testList "ReversePropertyTests" [

        testProperty "Char at index[length-n] of reversed string equals index[n] of original" <|
            fun (input:string) ->
                let reversed = reverse input

                if isNull input then
                    reversed = input
                else
                    // Account for zero-based index
                    let reversedLength = reversed.Length - 1
                    let reversedAsArray = reversed.ToCharArray()
                    input
                        |> Seq.mapi(fun i c -> c = reversedAsArray.[reversedLength - i])
                        |> Seq.forall id
                
       // This will likely fail, can you see why?
       testProperty "Reversed string should have same length as original" <|
            fun (input:string) ->
                let reversed = reverse input
                reversed.Length = input.Length
                
       // Think about what other testProperty could be defined here

    ]
```
<!--kg-card-end: markdown-->

This way, we are not testing any individual input. Instead FsCheck will, by default, run the test 100 times using progressively more complicated strings that include whitespace, line breaks, unprintable characters etc.

If a test fails, the framework will then restrict the inputs it generates based on the failing tests to try identify ranges of failure. When a failure is encountered it will attempt to reduce the failure to the minimum changes from passing tests required for it to fail.

In practice this means that if we were testing a method with DateTime parameters, it might be able to show us that there is an error in the method when dealing with dates in specific ranges or that only occur before or after particular dates.

It is also very adaptable, we can create custom data generators, allowing us to create random data within ranges or of specific types. For instance, you may want to create random email addresses or some other constrained type.

These are some of the properties we can test using a library like FsCheck. Obviously in this example the first property above is enough to define the method entirely but in more complex scenarios, it can be better to have a number of tests that each check an individual property of the scenario. An example of this is Mark Seemann's excellent [Introduction to Property Based Testing](https://www.pluralsight.com/courses/fsharp-property-based-testing-introduction) on Pluralsight which utilises the [Diamond Kata](https://codingdojo.org/kata/Diamond/) as a demonstration.

FsCheck is a .NET library so although it is written in F# and primarily with the F# ecosystem in mind it can be used just as easily in C# or VB.NET. It uses a `PropertyAttribute` or any custom attribute which inherits from it. Although the examples here are written using [Expecto](https://github.com/haf/expecto) and its [FsCheck plugin](https://www.nuget.org/packages/Expecto.FsCheck/), there are also plugins for [xUnit](https://www.nuget.org/packages/FsCheck.Xunit/) and [NUnit](https://www.nuget.org/packages/FsCheck.Nunit/).

Property based testing is a different method of thinking about your tests but something well worth considering, especially for those areas of your codebase that seem to always have more edge cases every time you look at them. By making you stop and think about the more generalised properties of what the method should be doing it flushes those edge cases out into the light where they can be found.