Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 37 ยท Interop and Tooling

Testing F# Code

Learn how to test F# code: xUnit and Expecto test projects, assertions, naming tests with backticks, testing pure functions and Results, property-based testing with FsCheck, and test organisation.

F# code is unusually easy to test. Most of it is made of pure functions over immutable data: give the function an input, check the output, nothing to mock and nothing to reset between tests. The hard part of testing is usually setup and hidden state, and F# design removes both. This lesson covers how to set up a test project, the main libraries, and a technique F# is famous for: property-based testing.

A test project

Terminal
dotnet new xunit -lang F# -o Calc.Tests
cd Calc.Tests
dotnet add reference ../Calc/Calc.fsproj
dotnet test

Suppose the library under test has this function:

FSHARP
module Calc.Pricing

let applyDiscount (percent: int) (price: decimal) =
    if percent < 0 || percent > 100 then Error "percent must be 0-100"
    else Ok (price * decimal (100 - percent) / 100m)

xUnit tests

xUnit is the default in the .NET world and works fine with F#. A test is a function with [<Fact>]:

FSHARP
module Calc.Tests.PricingTests

open Xunit
open Calc.Pricing

[<Fact>]
let ``ten percent off 200 is 180`` () =
    Assert.Equal(Ok 180m, applyDiscount 10 200m)

[<Fact>]
let ``negative percent is rejected`` () =
    Assert.Equal(Error "percent must be 0-100", applyDiscount -5 100m)

[<Theory>]
[<InlineData(0, 100)>]
[<InlineData(50, 50)>]
[<InlineData(100, 0)>]
let ``discount table`` (percent: int, expected: int) =
    Assert.Equal(Ok (decimal expected), applyDiscount percent 100m)

Double-backtick names ( like this ) let you write a test name as a sentence, and the sentence shows up in the test runner. Because a Result is a union with structural equality, Assert.Equal(Ok 180m, ...) compares the whole value, with no helper needed. For unions with %A printing the failure message is readable out of the box. [<Theory>] with [<InlineData>] runs one test over many rows.

C# C# stand-in: the same test logic as a plain runnable check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Expecto: tests as values

Expecto is an F#-native framework. Tests are ordinary values in lists, so you can generate them with loops and compose them like any other data:

FSHARP
open Expecto

let tests =
    testList "pricing" [
        test "ten percent off 200 is 180" {
            Expect.equal (applyDiscount 10 200m) (Ok 180m) "price"
        }

        testList "table" [
            for pct, expected in [ 0, 100m; 50, 50m; 100, 0m ] ->
                test $"{pct} percent" {
                    Expect.equal (applyDiscount pct 100m) (Ok expected) "price"
                }
        ]
    ]

[<EntryPoint>]
let main args = runTestsWithCLIArgs [] args tests

Generating a test per table row with a list comprehension is a nice illustration of "tests are data". Expecto test projects are plain console apps, so dotnet run runs them and debugging is trivial.

Testing Results and options

Because failures are values, error paths are as easy to test as success paths, and there is no Assert.Throws ceremony. A helper that unwraps makes intent clear:

FSHARP
let shouldBeOk = function
    | Ok v -> v
    | Error e -> failwithf "expected Ok but got Error %A" e

[<Fact>]
let ``valid discount produces a price`` () =
    let price = applyDiscount 25 80m |> shouldBeOk
    Assert.Equal(60m, price)

FsUnit adds a fluent syntax (price |> should equal 60m) if you prefer that style; Unquote lets you write assertions as ordinary boolean expressions (test <@ price = 60m @>) and prints a step-by-step evaluation on failure.

Property-based testing with FsCheck

Example tests check the inputs you thought of. Property-based tests state a rule that must hold for all inputs, and the library generates hundreds of random ones, including nasty edge cases. If a property fails, FsCheck shrinks the counterexample to the smallest input that still breaks it.

FSHARP
open FsCheck.Xunit

[<Property>]
let ``reversing twice returns the original list`` (xs: int list) =
    List.rev (List.rev xs) = xs

[<Property>]
let ``a discounted price is never more than the original`` (pct: byte) (cents: uint32) =
    let pct = int pct % 101
    let price = decimal cents / 100m
    match applyDiscount pct price with
    | Ok p -> p <= price
    | Error _ -> false

Good properties are about relationships: round trips (serialise then parse gives the original), invariants (sorting keeps the length), comparison with a simple model (a fast function equals a slow obvious one) and idempotence (doing it twice equals doing it once).

C# C# stand-in: a hand-rolled property check with a fixed seed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Organising tests

flowchart TD
    A["Unit tests<br/>pure functions, fast"] --> B["Integration tests<br/>database, HTTP"]
    B --> C["End-to-end tests<br/>few, slow"]
    A --- D["Property tests<br/>rules over random inputs"]

Most tests should be the cheap ones at the top: pure functions need no setup.

Tips: name tests as sentences; keep one test file per module (Pricing.fs and PricingTests.fs) with the test project mirroring the source layout; push I/O to the edges so the core is testable without mocks; pass dependencies as function arguments, and in tests pass a simple lambda instead of a mocking framework.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is F# code usually easy to test?

    With no hidden state, a test is just input, call, expected output.
  2. 2. What do double-backtick identifiers allow in test names?

    like this is a legal F# identifier and appears as written in the test report.
  3. 3. What is distinctive about Expecto?

    Expecto tests are ordinary F# values, so loops and list comprehensions can build them.
  4. 4. What does FsCheck do when a property fails?

    Shrinking reports the smallest input that still breaks the rule, which makes bugs easy to diagnose.

Summary

  • Create test projects with dotnet new xunit -lang F#; run them with dotnet test.
  • xUnit uses [<Fact>] and [<Theory>]; Expecto treats tests as data; FsUnit and Unquote tune the assertion style.
  • Results and options compare structurally, so error paths are as easy to test as success.
  • FsCheck checks rules over many random inputs and shrinks failures.
  • Keep logic pure and pass dependencies as functions to avoid mocking frameworks.

Next: Project: Bank Account Simulator