F# unit testing
last modified December 4, 2026
In this article we write unit tests for F# code with xUnit and run them
with dotnet test.
A unit test is a small function that calls a piece of our code with known input and checks the result. When a later change breaks the code, the test fails and tells us where. .NET has several test frameworks; xUnit is the most widely used and has an F# project template. F# libraries such as Expecto, FsUnit, and Unquote offer more F#-like syntax on top of the same ideas. Tests live in their own project, which references the project under test, as described in F# projects.
Creating the projects
We test a small pricing library. The classlib template
creates the library and the xunit template the test project.
The test project gets a reference to the library, and a solution groups
both. We show only the first line of each dotnet new output;
the rest is the log of the package restore.
λ dotnet new classlib -lang "F#" -o Pricing The template "Class Library" was created successfully. λ dotnet new xunit -lang "F#" -o Pricing.Tests The template "xUnit Test Project" was created successfully. λ dotnet add Pricing.Tests reference Pricing Reference `..\Pricing\Pricing.fsproj` added to the project. λ dotnet new sln -n Pricing The template "Solution File" was created successfully. λ dotnet sln add Pricing Pricing.Tests Project `Pricing/Pricing.fsproj` added to the solution. Project `Pricing.Tests/Pricing.Tests.fsproj` added to the solution.
The code under test
We delete the generated Library.fs and
Tests.fs. The first module of the library computes a
discount for an order total.
module Pricing.Discount
let rate (total: float) =
if total >= 100.0 then 0.10
elif total > 50.0 then 0.05
else 0.0
let apply (total: float) = total - total * rate total
Orders of 100 or more get ten percent off and orders of 50 or more get
five percent. The second condition has a bug that we find later: it uses
> instead of >=.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="Discount.fs" />
</ItemGroup>
</Project>
The library project compiles one file. Later sections add more modules;
each new file gets its own Compile item.
The first tests
An xUnit test is a function marked with the [<Fact>]
attribute. It takes unit and returns unit; it passes when it returns and
fails when it throws an exception. The Assert class has
methods that throw when a check fails.
module DiscountTests
open Xunit
open Pricing
[<Fact>]
let ``small orders get no discount`` () =
Assert.Equal(0.0, Discount.rate 30.0)
[<Fact>]
let ``orders of 100 or more get ten percent`` () =
Assert.Equal(0.10, Discount.rate 100.0)
Assert.Equal(90.0, Discount.apply 100.0)
Names in double backticks may contain spaces, so a test name can be a
sentence that says what the code should do. Assert.Equal
takes the expected value first and the actual value second; the order
matters for the failure message.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<Compile Include="DiscountTests.fs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Pricing\Pricing.fsproj" />
</ItemGroup>
</Project>
The template added the packages: xunit is the framework,
xunit.runner.visualstudio and
Microsoft.NET.Test.Sdk let dotnet test find and
run the tests, and coverlet.collector measures code coverage.
dotnet add reference added the
ProjectReference, and we replaced Tests.fs with
DiscountTests.fs.
dotnet test in the solution directory builds both projects
and runs the tests. With -v q it shows only the summary.
The durations vary from run to run.
λ dotnet test -v q Test run for Pricing.Tests/bin/Debug/net11.0/Pricing.Tests.dll (.NETCoreApp,Version=v11.0) A total of 1 test files matched the specified pattern. Passed! - Failed: 0, Passed: 2, Skipped: 0, Total: 2, Duration: 19 ms - Pricing.Tests.dll (net11.0)
A failing test
We add a test for the boundary of the middle tier. Values at the edge of a condition are where bugs hide.
module DiscountTests
open Xunit
open Pricing
[<Fact>]
let ``small orders get no discount`` () =
Assert.Equal(0.0, Discount.rate 30.0)
[<Fact>]
let ``orders of 50 get five percent`` () =
Assert.Equal(0.05, Discount.rate 50.0)
[<Fact>]
let ``orders of 100 or more get ten percent`` () =
Assert.Equal(0.10, Discount.rate 100.0)
Assert.Equal(90.0, Discount.apply 100.0)
Without -v q, dotnet test prints the build
lines and the details of each failure: the test name, the expected and
actual values, and a stack trace with the file and line of the failed
assertion. We have shortened the paths. xUnit prints floats with 17
significant digits, so the expected 0.05 appears as
0.050000000000000003, the closest binary value.
λ dotnet test
Determining projects to restore...
All projects are up-to-date for restore.
Pricing -> Pricing/bin/Debug/net11.0/Pricing.dll
Pricing.Tests -> Pricing.Tests/bin/Debug/net11.0/Pricing.Tests.dll
Test run for Pricing.Tests/bin/Debug/net11.0/Pricing.Tests.dll (.NETCoreApp,Version=v11.0)
A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:00.18] DiscountTests.orders of 50 get five percent [FAIL]
Failed DiscountTests.orders of 50 get five percent [2 ms]
Error Message:
Assert.Equal() Failure: Values differ
Expected: 0.050000000000000003
Actual: 0
Stack Trace:
at DiscountTests.orders of 50 get five percent() in Pricing.Tests/DiscountTests.fs:line 12
at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
Failed! - Failed: 1, Passed: 2, Skipped: 0, Total: 3, Duration: 32 ms - Pricing.Tests.dll (net11.0)
Theories
The failure points at the > in rate; we
change it to >=. Checking many inputs with one fact per
input is repetitive. A theory is a test with parameters, and each
[<InlineData>] attribute gives one set of arguments.
module DiscountTests
open Xunit
open Pricing
[<Theory>]
[<InlineData(0.0, 0.0)>]
[<InlineData(49.99, 0.0)>]
[<InlineData(50.0, 0.05)>]
[<InlineData(99.99, 0.05)>]
[<InlineData(100.0, 0.10)>]
[<InlineData(250.0, 0.10)>]
let ``discount rate by total`` (total: float, expected: float) =
Assert.Equal(expected, Discount.rate total)
[<Fact>]
let ``discount is subtracted from the total`` () =
Assert.Equal(90.0, Discount.apply 100.0)
The parameters of a theory are written in tupled form, because xUnit
calls the test like a .NET method. Attribute arguments must be constants,
so InlineData takes numbers, strings, and Booleans, but not
F# lists or records.
--list-tests shows the test cases that xUnit found without
running them; each InlineData row is a separate case, shown
with its arguments.
λ dotnet test -v q --list-tests
Test run for Pricing.Tests/bin/Debug/net11.0/Pricing.Tests.dll (.NETCoreApp,Version=v11.0)
The following Tests are available:
DiscountTests.discount rate by total(total: 0, expected: 0)
DiscountTests.discount rate by total(total: 49.990000000000002, expected: 0)
DiscountTests.discount rate by total(total: 50, expected: 0.050000000000000003)
DiscountTests.discount rate by total(total: 99.989999999999995, expected: 0.050000000000000003)
DiscountTests.discount rate by total(total: 100, expected: 0.10000000000000001)
DiscountTests.discount rate by total(total: 250, expected: 0.10000000000000001)
DiscountTests.discount is subtracted from the total
λ dotnet test -v q
Test run for Pricing.Tests/bin/Debug/net11.0/Pricing.Tests.dll (.NETCoreApp,Version=v11.0)
A total of 1 test files matched the specified pattern.
Passed! - Failed: 0, Passed: 7, Skipped: 0, Total: 7, Duration: 19 ms - Pricing.Tests.dll (net11.0)
Testing Result values
F# values with structural equality, such as lists, tuples, records,
options, and Result, can be compared directly with
Assert.Equal. We add a module that parses a quantity from
text.
module Pricing.Quantity
open System
let parse (text: string) =
match Int32.TryParse(text.Trim()) with
| true, n when n > 0 -> Ok n
| true, _ -> Error "quantity must be positive"
| false, _ -> Error $"not a number: {text}"
parse returns Ok with the number or
Error with a message, as in
F# Result type. We add
Quantity.fs after Discount.fs in the library
project file.
module QuantityTests
open Xunit
open Pricing
[<Fact>]
let ``parses a number with spaces`` () =
Assert.Equal(Ok 3, Quantity.parse " 3 ")
[<Fact>]
let ``rejects zero`` () =
Assert.Equal(Error "quantity must be positive", Quantity.parse "0")
[<Fact>]
let ``rejects text`` () =
let result = Quantity.parse "three"
Assert.True(Result.isError result)
The expected Ok 3 and the actual result are equal when both
cases and their contents are equal. When only the kind of result matters,
Assert.True checks a Boolean. We add
QuantityTests.fs to the test project file.
λ dotnet test -v q Test run for Pricing.Tests/bin/Debug/net11.0/Pricing.Tests.dll (.NETCoreApp,Version=v11.0) A total of 1 test files matched the specified pattern. Passed! - Failed: 0, Passed: 10, Skipped: 0, Total: 10, Duration: 44 ms - Pricing.Tests.dll (net11.0)
Testing exceptions
Some functions throw on invalid input, as described in F# exceptions. A test can require the exception. We add a module that splits a bill among several people.
module Pricing.Split
let perPerson (total: float) (people: int) =
if people <= 0 then
invalidArg (nameof people) "must be at least one person"
total / float people
invalidArg throws an ArgumentException with
the name of the parameter. The file goes after Quantity.fs
in the library project.
module SplitTests
open System
open Xunit
open Pricing
[<Fact>]
let ``splits a bill evenly`` () =
Assert.Equal(25.0, Split.perPerson 100.0 4)
[<Fact>]
let ``zero people is an error`` () =
let ex = Assert.Throws<ArgumentException>(fun () -> Split.perPerson 100.0 0 |> ignore)
Assert.Equal("people", ex.ParamName)
Assert.Throws runs the lambda and passes if it throws an
exception of exactly the given type. It returns the exception, so we can
check its details. The lambda must return unit, hence the
ignore. We add SplitTests.fs to the test
project.
λ dotnet test -v q Test run for Pricing.Tests/bin/Debug/net11.0/Pricing.Tests.dll (.NETCoreApp,Version=v11.0) A total of 1 test files matched the specified pattern. Passed! - Failed: 0, Passed: 12, Skipped: 0, Total: 12, Duration: 43 ms - Pricing.Tests.dll (net11.0)
Floating-point numbers
Results of floating-point arithmetic are rarely exact, so comparing them with plain equality makes fragile tests. We add two tests for a bill that does not divide evenly.
module SplitTests
open System
open Xunit
open Pricing
[<Fact>]
let ``splits a bill evenly`` () =
Assert.Equal(25.0, Split.perPerson 100.0 4)
[<Fact>]
let ``zero people is an error`` () =
let ex = Assert.Throws<ArgumentException>(fun () -> Split.perPerson 100.0 0 |> ignore)
Assert.Equal("people", ex.ParamName)
[<Fact>]
let ``uneven split, exact`` () =
Assert.Equal(0.1, Split.perPerson 0.3 3)
[<Fact>]
let ``uneven split, rounded`` () =
Assert.Equal(0.1, Split.perPerson 0.3 3, 10)
In binary floating point, 0.3 / 3 is 0.09999999999999999, not 0.1, so
the exact test fails. The third argument of Assert.Equal for
floats is the number of decimal places to which both values are rounded
before the comparison; with it the second test passes.
Assert.Equal also has an overload that takes a tolerance as
a float. With -v q the failure details are hidden; the
--logger option with minimal console verbosity brings them
back without the build lines.
λ dotnet test -v q --logger "console;verbosity=minimal"
Test run for Pricing.Tests/bin/Debug/net11.0/Pricing.Tests.dll (.NETCoreApp,Version=v11.0)
A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:00.21] SplitTests.uneven split, exact [FAIL]
Failed SplitTests.uneven split, exact [1 ms]
Error Message:
Assert.Equal() Failure: Values differ
Expected: 0.10000000000000001
Actual: 0.099999999999999992
Stack Trace:
at SplitTests.uneven split, exact() in Pricing.Tests/SplitTests.fs:line 18
at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
Failed! - Failed: 1, Passed: 13, Skipped: 0, Total: 14, Duration: 44 ms - Pricing.Tests.dll (net11.0)
Asynchronous tests
A test may return a Task; xUnit waits for it to finish. This
lets us test code written with task expressions, covered in
F# async and tasks. We remove the
exact float test and add a module that loads a price list from a file.
module Pricing.PriceList
open System.IO
let load (path: string) =
task {
let! lines = File.ReadAllLinesAsync path
return
lines
|> Array.map (fun line ->
let parts = line.Split ','
parts[0], float parts[1])
|> Map.ofArray
}
Each line of the file has a product name and a price separated by a
comma. load returns a Task<Map<string,
float>>. The file goes last in the library project.
module PriceListTests
open System.IO
open Xunit
open Pricing
[<Fact>]
let ``loads prices from a file`` () =
task {
let path = Path.GetTempFileName()
do! File.WriteAllLinesAsync(path, [| "apple,0.45"; "bread,2.10" |])
let! prices = PriceList.load path
File.Delete path
Assert.Equal(2, prices.Count)
Assert.Equal(2.10, prices["bread"])
}
The test writes a temporary file, loads it, deletes it, and checks the
map. Because the test returns a Task, any failed assertion
inside the task block fails the test. We add
PriceListTests.fs to the test project.
λ dotnet test -v q Test run for Pricing.Tests/bin/Debug/net11.0/Pricing.Tests.dll (.NETCoreApp,Version=v11.0) A total of 1 test files matched the specified pattern. Passed! - Failed: 0, Passed: 14, Skipped: 0, Total: 14, Duration: 44 ms - Pricing.Tests.dll (net11.0)
Setup and cleanup
In the last test the file is not deleted when an assertion before
File.Delete fails. Tests can also be members of a class.
xUnit creates a new instance of the class for each test, so the
constructor prepares the data, and if the class implements
IDisposable, xUnit calls Dispose after each
test, whether it passed or failed.
module PriceListTests
open System
open System.IO
open Xunit
open Pricing
type PriceListTests() =
let path = Path.GetTempFileName()
do File.WriteAllLines(path, [| "apple,0.45"; "bread,2.10"; "milk,0.89" |])
[<Fact>]
member _.``loads every line`` () =
task {
let! prices = PriceList.load path
Assert.Equal(3, prices.Count)
}
[<Fact>]
member _.``keeps the prices`` () =
task {
let! prices = PriceList.load path
Assert.Equal(0.89, prices["milk"])
}
interface IDisposable with
member _.Dispose() = File.Delete path
Each test gets its own temporary file, created in the constructor and
deleted in Dispose. Test methods are members with the
[<Fact>] attribute. Classes and interfaces are covered
in F# classes and
F# interfaces.
λ dotnet test -v q Test run for Pricing.Tests/bin/Debug/net11.0/Pricing.Tests.dll (.NETCoreApp,Version=v11.0) A total of 1 test files matched the specified pattern. Passed! - Failed: 0, Passed: 15, Skipped: 0, Total: 15, Duration: 49 ms - Pricing.Tests.dll (net11.0)
Running selected tests
In a large project we often run only the tests we are working on.
The --filter option selects tests by name. The
FullyQualifiedName of a test includes its module, so
~ (contains) with a module name selects all tests of the
module.
λ dotnet test -v q --filter "FullyQualifiedName~QuantityTests" Test run for Pricing.Tests/bin/Debug/net11.0/Pricing.Tests.dll (.NETCoreApp,Version=v11.0) A total of 1 test files matched the specified pattern. Passed! - Failed: 0, Passed: 3, Skipped: 0, Total: 3, Duration: 23 ms - Pricing.Tests.dll (net11.0) λ dotnet test -v q --filter "DisplayName~rate" Test run for Pricing.Tests/bin/Debug/net11.0/Pricing.Tests.dll (.NETCoreApp,Version=v11.0) A total of 1 test files matched the specified pattern. Passed! - Failed: 0, Passed: 6, Skipped: 0, Total: 6, Duration: 17 ms - Pricing.Tests.dll (net11.0)
Source
Unit testing F# libraries in .NET with dotnet test and xUnit
In this article we have tested an F# library with xUnit. We have created
a test project, written facts and theories, read the output of a failing
test, compared Result values, required exceptions, compared
floats with rounding, written asynchronous tests, used a test class for
setup and cleanup, and run selected tests. Projects and solutions are
covered in F# projects; the next article
is F# JSON.
Author
List all F# tutorials.