F#: Unit Testing a ViewModel

Intro

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.

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
FSharp_TestProject
3. On your test project, add the NuGet package, “FSUnit”.
FSUnit_Nuget

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

NUnit_reference

Unit Test

Here’s a unit test:

module UnitTests
open Model
open FsUnit
open NUnit.Framework

[<Test>]
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())

 

Conclusion

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

=)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: