F# development and unit testing?

As dglaubman suggests you can use NUnit. xUnit.net also provides support for this and works well with TestDriven.net. The code looks similar to NUnit tests but without the requirement to wrap the test in a containing type.

#light

// Supply a module name here not a combination of module and namespace, otherwise
// F# cannot resolve individual tests nfrom the UI.
module NBody.DomainModel.FSharp.Tests

open System
open Xunit

open Internal

[<Fact>]
let CreateOctantBoundaryReordersMinMax() =
    let Max = VectorFloat(1.0, 1.0, 1.0)
    let Min = VectorFloat(-1.0, -1.0, -1.0)

    let result = OctantBoundary.create Min Max

    Assert.Equal(Min, result.Min)     
    Assert.Equal(Max, result.Max) 

Have a look at FsCheck, an automatic testing tool for F#, is basically a port of Haskell's QuickCheck. It allows you to provide a specification of the program, in the form of properties that the functions or methods should satisfy, and FsCheck tests that the properties hold in a large number of randomly generated cases.

FsCheck CodePlex Page

FsCheck Author Page


Test-driven developers should feel right at home in functional languages like F#: small functions that give deterministically repeatable results lend themselves perfectly to unit tests. There are also capabilities in the F# language that facilitate writing tests. Take, for example, Object Expressions. You can very easily write fakes for functions that take as their input an interface type.

If anything, F# is a first-class object-oriented language and you can use the same tools and tricks that you use when doing TDD in C#. There are also some testing tools written in or specifically for F#:

  • NaturalSpec
  • FsCheck
  • FsTest
  • FsUnit

Matthew Podwysocki wrote a great series on unit testing in functional languages. Uncle Bob also wrote a thought provoking article here.


I use NUnit, and it doesn't strike me as hard to read or onerous to write:

open NUnit.Framework

[<TestFixture>]
type myFixture() = class

    [<Test>]
    member self.myTest() =
       //test code

end

Since my code is a mix of F# and other .Net languages, I like the fact that I write the unit tests in basically the same fashion and with similar syntax in both F# and C#.