Unit tests are essential for building software effectively. In addition, unit tests also enable developers to exterminate bugs quickly with extreme prejudice.

Protect this House from Bugs

I thought that I could use the video above as a metaphor so that I could hype-up my craftsman such as yourself into protecting your codebase with a defense-hungry mentality.

Now in a previous article, I provided a tutorial on how to implement MVVM using F# and WPF. However, in this article, I will provide an example of how to unit test a viewmodel.


Here’s a viewmodel:

namespace Model

    type ViewModel() =
        inherit ViewModelBase()

        let mutable firstName = "Scott"
        let mutable lastName = "Nimrod"

        member this.FirstName
            with get() = firstName 
            and set(value) = firstName <- value
                             base.NotifyPropertyChanged(<@ this.FirstName @>)
        member this.LastName
            with get() = lastName 
            and set(value) = lastName <- value
                             base.NotifyPropertyChanged(<@ this.LastName @>)

        member this.GetFullName() = 
            sprintf "%s %s" (this.FirstName) (this.LastName)

Now in order for us to unit test this viewmodel, we first need to employ some tools in order for us to perform this ceremony. I prefer to use FSUnit in conjunction with the NUnit framework. These two frameworks enable me to write some pretty concise and legible unit tests.

Perform the following steps:

  1. Download and install the NUnit extension from the NUnit website.
  2. Add a new F# library to your solution
3. On your test project, add the NuGet package, “FSUnit”.

4. Add the reference, “NUnit.Framework” to your test project


Unit Test

Here’s a unit test:

module UnitTests
open Model
open FsUnit
open NUnit.Framework

member __.``GetFullName = "Jon Doe" if FirstName = "Jon" and LastName = "Doh"``() =
    let vm = ViewModel()
    vm.FirstName <- "Jon"
    vm.LastName <- "Doe"

    Assert.AreEqual("Jon Doe", vm.GetFullName())



In conclusion, I just provided an example of how to unit test a viewmodel. Enjoy!