In my previous post we setup a basic F# project in Linux.
In this post I would like to show how to setup an idiomatic F# testing environment using FsUnit.
Side note for people unfamiliar with .NET
Actually, it’s not a project, but a “solution”. To clear things up for people not familiar with the .NET ecosystem: In .NET, the top level configuration is called a “solution” and resides in a
*.sln file. A solution references “projects”. Each project configuration is stored in a
*.fsproj file (F#) or a
*.csproj file (C#). Projects can reference each other. This information is stored in the
We have 2 projects (
FizzBuzz.Tests), each with a
*.fsproj file. The
FizzBuzz.Tests.fsproj references the
FizzBuzz.fsproj file (see the previous post for details):
1 2 3 4 5 6 7 8
This is the current state of our test:
1 2 3 4
[<Fact>]: this is F#’s annotation style. The same as C#
Array with Number 1 returns 'one': Method name in double back-ticks improves readability, especially in unit tests. No CamelCasing or snake_casing needed. It’s an F# language feature.
Assert.Equal(...): This is probably familiar to everyone who has ever written a unit test. Every assertion library has a different signature: Is it
Equal(actual, expected)? I hate this! Thankfully there are alternative assertion libraries. Example: In C# you can write
FluentAssertions). The same is true for F#.
FsUnit: Idiomatic assertions
What does “idiomatic” mean? For programming languages, it means: Writing code as most people, who are used to the language, would write the code (how a “native” would express an idea, a concept, an algorithm, etc). Simple example: In Java and JS, the first character of a method name should be lower case. In C#, the first character should be upper case (yes, even if the method is private!). The code will still compile if you don’t comply to these conventions, but it’s not “idiomatic”. Same goes for “For Loops” vs using a “Map” functions: In some languages one concept is preferred over the other.
FsUnit brings pipes to F# unit tests. Pipes are used extensively in F# and should be familiar to most linux shell users: Bash uses the
| symbol as operator to redirect the output of one expression to the input of another expression. In F# the pipe operator is
|>. The concept might seem similar to using “Method Chaining” in C# (it’s not, but close enough in this context).
1 2 3 4 5
FizzBuzz.Tests/FizzBuzz.Tests.fsproj should now look like this (plus/minus some version numbers):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
Note the line
<PackageReference Include="FsUnit.Xunit" Version="3.0.0" /> (your version number might differ).
Modify the test file
FizzBuzz.Tests/Tests.fs to look like this:
1 2 3 4 5 6 7 8 9 10 11
Running the unit tests within the test folder:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
We can now write unit tests in an F# way (“idiomatic”) by using the library
Have fun with F# and linux!
Get the source code here